java之学习笔记(13)-------------数组学习以及循环机制中for each讲解

来源:互联网 发布:网络机顶盒安装步骤 编辑:程序博客网 时间:2024/05/22 10:26

数组详细解析!

数组中可分为以下几种:一维数组、二维数组、以及多维数组。

定义数组

  方式1(推荐,更能表明数组类型)

  type[] 变量名 = new type[数组中元素的个数];

  比如:

  int[] a = new int[10];

  数组名,也即引用a,指向数组元素的首地址。

  方式2(同C语言)

  type变量名[] = new type[数组中元素的个数];

  如:

  int a[] = new int[10];

  方式3定义时直接初始化

  type[] 变量名 = new type[]{逗号分隔的初始化值};

  其中红色部分可省略,所以又有两种:

  int[] a = {1,2,3,4};

  int[] a = new int[]{1,2,3,4};

  其中int[] a = new int[]{1,2,3,4};的第二个方括号中不能加上数组长度,因为元素个数是由后面花括号的内容决定的。

 

数组运用基础

数组长度

  Java中的每个数组都有一个名为length的属性,表示数组的长度。

  length属性是public final int的,即length是只读的。数组长度一旦确定,就不能改变大小。

equals()

  数组内容的比较可以使用equals()方法吗?

  如下程序:

  

复制代码
public class ArrayTest{      public static void main(String[] args)      {             int[] a = {1, 2, 3};             int[] b = {1, 2, 3};             System.out.println(a.equals(b));      }    }
复制代码

  输出结果是false。

  所以证明不能直接用equals()方法比较数组内容,因为没有override Object中的实现,所以仍采用其实现,即采用==实现equals()方法,比较是否为同一个对象。

  怎么比较呢?一种解决方案是自己写代码,另一种方法是利用java.util.Arrays

  java.util.Arrays中的方法全是static的。其中包括了equals()方法的各种重载版本。

  代码如下:

ArrayEqualsTest.java
import java.util.Arrays;public class ArrayEqualsTest{    //Compare the contents of two int arrays    public static boolean isEquals(int[] a, int[] b)    {        if( a == null || b == null )        {             return false;        }        if(a.length != b.length)        {            return false;        }        for(int i = 0; i < a.length; ++i )        {            if(a[i] != b[i])            {                return false;            }        }        return true;    }    public static void main(String[] args)    {        int[] a = {1, 2, 3};        int[] b = {1, 2, 3};        System.out.println(isEquals(a,b));        System.out.println(Arrays.equals(a,b));    }}

 

数组元素不为基本数据类型时

  数组元素不为基本原生数据类型时,存放的是引用类型,而不是对象本身。当生成对象之后,引用才指向对象,否则引用为null。

  如下列程序:

ArrayTest2.java
public class ArrayTest2{    public static void main(String[] args)    {        Person[] p = new Person[3];        //未生成对象时,引用类型均为空        System.out.println(p[0]);        //生成对象之后,引用指向对象        p[0] = new Person(10);        p[1] = new Person(20);        p[2] = new Person(30);        for(int i = 0; i < p.length; i++)        {            System.out.println(p[i].age);        }    }}class Person{    int age;    public Person(int age)    {        this.age = age;    }}

 

  输出:

  null

  10

  20

  30

  也可以在初始化列表里面直接写:

  Person[] p = new Person[]{new Person(10), new Person(20), new Person(30)};

 

二维数组

  二维数组是数组的数组。

 

二维数组基础

  基本的定义方式有两种形式,如:

  type[][] i = new type[2][3];(推荐)

  type i[][] = new type[2][3];

  如下程序:

 

复制代码
public class ArrayTest3{      public static void main(String[] args)      {             int[][] i = new int[2][3];             System.out.println("Is i an Object? "                           + (i instanceof Object));             System.out.println("Is i[0] an int[]? "                           + (i[0] instanceof int[]));      }}
复制代码

 

  输出结果是两个true。

 

变长的二维数组

  二维数组的每个元素都是一个一维数组,这些数组不一定都是等长的。

  声明二维数组的时候可以只指定第一维大小,空缺出第二维大小,之后再指定不同长度的数组。但是注意,第一维大小不能空缺(不能只指定列数不指定行数)。

  如下程序:

 

复制代码
public class ArrayTest4{    public static void main(String[] args)    {        //二维变长数组        int[][] a = new int[3][];        a[0] = new int[2];        a[1] = new int[3];        a[2] = new int[1];        //Error: 不能空缺第一维大小        //int[][] b = new int[][3];    }}
复制代码

 

  二维数组也可以在定义的时候初始化,使用花括号的嵌套完成,这时候不指定两个维数的大小,并且根据初始化值的个数不同,可以生成不同长度的数组元素。

  如下程序:

  

复制代码
public class ArrayTest5{    public static void main(String[] args)    {        int[][] c = new int[][]{{1, 2, 3},{4},{5, 6, 7, 8}};        for(int i = 0; i < c.length; ++i)        {            for(int j = 0; j < c[i].length; ++j)            {                System.out.print(c[i][j]+" ");                    }            System.out.println();        }            }}
复制代码

 

  输出:

  1 2 3

  4

  5 6 7 8

 

下面讲解三维数组,面试的时候我曾在笔试中遇到过!

也许会有一定的帮助!

定义:

type[][][]str= new str[4][2][3];

在像数组中添加数值的过程,

str[0][0][0],str[0][0][1],str[0][0][2];

str[0][1][0];str[0][1][1];str[0][1][2];

str[1][0][0];str[1][0][1];str[1][0][2];

str[1][1][0];str[1][1][1];str[1][1][2];

..........

 

多维数组的添加数值的方式,类似于二进制的增进过程,逐级的向上增加。

 

for each的学习

 

 

foreach语句是java5的新特征之一,在遍历数组、集合方面,foreach为开发人员提供了极大的方便。
 
foreach语句是for语句的特殊简化版本,但是foreach语句并不能完全取代for语句,然而,任何的foreach语句都可以改写为for语句版本。
 
foreach并不是一个关键字,习惯上将这种特殊的for语句格式称之为“foreach”语句。从英文字面意思理解foreach也就是“for 每一个”的意思。实际上也就是这个意思。
 
foreach的语句格式:
for(元素类型t 元素变量x : 遍历对象obj){
     引用了x的java语句;
}
 
下面通过两个例子简单例子看看foreach是如何简化编程的。代码如下:
 
一、foreach简化数组和集合的遍历
 
import java.util.Arrays;
import java.util.List; 
import java.util.ArrayList; 

/**
* Created by IntelliJ IDEA. 
* User: leizhimin 
* Date: 2007-12-3 
* Time: 16:58:24 
* Java5新特征之foreach语句使用总结 
*/
 
publicclass TestArray { 
    public static void main(String args[]) { 
        TestArray test = new TestArray(); 
        test.test1(); 
        test.listToArray(); 
        test.testArray3(); 

    } 

    
/**
     * foreach语句输出一维数组 
     */
 
    
publicvoid test1() { 
        //定义并初始化一个数组 
        int arr[] = {2, 3, 1}; 
        System.out.println("----1----排序前的一维数组");
        for (int x : arr) {
            System.out.println(x); //逐个输出数组元素的值 
        } 

        //对数组排序 
        Arrays.sort(arr); 

        //利用java新特性for each循环输出数组 
        System.out.println("----1----排序后的一维数组");
        for (int x : arr) {
            System.out.println(x); //逐个输出数组元素的值 
        } 
    } 

    
/**
     * 集合转换为一维数组 
     */
 
    
publicvoid listToArray() { 
        //创建List并添加元素 
        List<String> list = new ArrayList<String>();
        list.add("1"); 
        list.add("3"); 
        list.add("4"); 

        //利用froeach语句输出集合元素 
        System.out.println("----2----froeach语句输出集合元素");
        for (String x : list) { 
            System.out.println(x); 
        } 

        //将ArrayList转换为数组 
        Object s[] = list.toArray(); 

        //利用froeach语句输出集合元素 
        System.out.println("----2----froeach语句输出集合转换而来的数组元素");
        for (Object x : s) { 
            System.out.println(x.toString()); //逐个输出数组元素的值
        } 
    } 

    
/**
     * foreach输出二维数组测试 
     */
 
    
publicvoid testArray2() { 
        int arr2[][] = {{4, 3}, {1, 2}};
        System.out.println("----3----foreach输出二维数组测试");
        for (int x[] : arr2) {
            for (int e : x) {
                System.out.println(e); //逐个输出数组元素的值 
            } 
        } 
    } 

    
/**
     * foreach输出三维数组 
     */
 
    
publicvoid testArray3() { 
        int arr[][][] = { 
                {{1, 2}, {3, 4}}, 
                {{5, 6}, {7, 8}} 
        }; 

        System.out.println("----4----foreach输出三维数组测试");
        for (int[][] a2 : arr) {
            for (int[] a1 : a2) {
                for (int
 x : a1) {
                    System.out.println(x); 
                } 
            } 
        } 
    } 
}
 
运行结果:
----1----排序前的一维数组 



----1----排序后的一维数组 



----2----froeach语句输出集合元素 



----2----froeach语句输出集合转换而来的数组元素 



----4----foreach输出三维数组测试 









Process finished with exit code 0
 
二、foreach语句的局限性
 
通过上面的例子可以发现,如果要引用数组或者集合的索引,则foreach语句无法做到,foreach仅仅老老实实地遍历数组或者集合一遍。下面看一个例子就明白了:
 
/**
* Created by IntelliJ IDEA. 
* User: leizhimin 
* Date: 2007-12-3 
* Time: 17:07:30 
* foreach语句的局限性 
*/
 
publicclass TestArray2 { 

    public static void main(String args[]) { 
        //定义一个一维数组 
        int arr[] = new int[4]; 
        System.out.println("----未赋值前输出刚刚定义的数组----");
        for (int x : arr) {
            System.out.println(x); 
        } 

        //通过索引给数组元素赋值 
        System.out.println("----通过循环变量给数组元素赋值----");
        for (int i = 3; i > 0; i--) {
            arr[i] = i; 
        } 
        //循环输出创建的数组 
        System.out.println("----赋值后,foreach输出创建好的数组----");
        for (int
 x : arr) {
            System.out.println(x); 
        } 
    } 
}

运行结果:
 
----未赋值前输出刚刚定义的数组---- 




----通过循环变量给数组元素赋值---- 
----赋值后,foreach输出创建好的数组---- 





Process finished with exit code 0
 
三、总结
 
foreach语句是for语句特殊情况下的增强版本,简化了编程,提高了代码的可读性和安全性(不用怕数组越界)。相对老的for语句来说是个很好的补充。提倡能用foreach的地方就不要再用for了。在用到对集合或者数组索引的情况下,foreach显得力不从心,这个时候是用for语句的时候了。
0 0