数组的遍历

1.for循环遍历

通常遍历数组都是使用for循环来实现。遍历一维数组很简单,遍历二维数组需要使用双层for循环,通过数组的length属性可获得数组的长度。

程序:

public class set0927 {
    public static void main(String[] args){
        int arr[][]={{5,22,13},{33,54,22},{45,78,99}};
        for (int i=0;i<arr.length;i++){
            for(int j=0;j<arr[i].length;j++){
                System.out.println(arr[i][j]+"");
            }
        }
    }
}

2.foreach语句遍历

遍历数组就是获取数组的每个元素。通常遍历数组都是使用for循环来实现的,但是for循环不够简洁,下面我们简要介绍一下使用foreach语句来实现遍历数组的方法。

java5之后,Java提供了一种更简洁的循环:foreach循环,这种循环遍历数组和集合更加简洁。使用foreach循环遍历数组时,无须获得数组和集合长度,无须根据索(下标)引来访问数组元素,foreach循环自动遍历数组和集合的每一个元素。

注:

foreach 语句为数组或对象集合中的每个元素重复一个嵌入语句组。foreach 语句用于循环访问集合以获取所需信息,但不应用于更改集合内容以避免产生不可预知的副作用。
因此不要对foreach的循环变量赋值。
例如:

public class set0927 {
    public static void main(String[] args) {
        int arr[][]={{5,22,13},{33,54,22},{45,78,99}};
        System.out.println("数组中的元素是");
        int i=0;
        for (int x[]:arr){ //行
            i++;
            int j=0;
            for(int e:x){// 列
                j++;
                if(i==arr.length&&j==x.length){
                   System.out.println(e);//输出最后一个元素
                }else
                    System.out.println(e+"");
                }
        }
    }
}

3.Arrays工具类中toString静态方法遍历

利用Arrays工具类中的toString静态方法可以将一维数组转化为字符串形式并输出。

已知打印一维数组的APISystem.out.println ( Arrays.toString ();,其参数为数组名或数组指针,其支持的数据类型有很多,如:int[]char[]byte[]等。

程序:

public class set0926 {
    public static void main(String[] args){
        int arr[][]={{1,2,3},{11,22,33},{123,456,789}};
        System.out.println("arr:"+ Arrays.toString(arr));
        int b[][]={{12,23,34},{11,22,33},{4,6,9}};
        System.out.println("arr:"+Arrays.deepToString(b));
    }
}

原文地址:https://www.cnblogs.com/yhcTACK/p/15345989.html