zoukankan      html  css  js  c++  java
  • Java中遍历数组的三种方式复习

    1 for循环遍历

    通常遍历数组都是使用for循环来实现。遍历一维数组很简单,遍历二维数组需要使用双层for循环,通过数组的length属性可获得数组的长度。
    程序示例:
    [java] view plain copy
     
    1. package captain;  
    2.   
    3. public class ArrayDemo {  
    4.       
    5.     public static void main(String[] args) {  
    6.         // TODO Auto-generated method stub  
    7.         int arr[][] = new int[][]{{1},{2,3},{4,5,6}};  
    8.           
    9.         //for循环遍历二维数组。  
    10.         for(int i = 0; i < arr.length; i++){  
    11.             for(int j = 0; j < arr[i].length; j++){  
    12.                 System.out.print(arr[i][j]);  
    13.             }  
    14.             System.out.println();  
    15.         }  
    16.   
    17.     }  
    18.   
    19. }  

    2 foreach语句遍历

    在遍历数组时,使用foreach语句更简单。
    程序示例:
    [java] view plain copy
     
    1. package captain;  
    2.   
    3. public class ArrayDemo2 {  
    4.   
    5.     public static void main(String[] args) {  
    6.         // TODO Auto-generated method stub  
    7.         int arr[][] = new int[][]{{4,3},{1,5}};  
    8.           
    9.         //foreach语句遍历二维数组。  
    10.         System.out.println("数组中的元素是:");  
    11.         for(int x[]:arr){  //外层遍历得到一维数组  
    12.             for(int e:x){  //内层遍历得到数组元素  
    13.                     System.out.print(e);  
    14.             }  
    15.             System.out.println();  
    16.         }  
    17.   
    18.     }  
    19.   
    20. }  

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

    利用Arrays工具类中的toString静态方法可以将一维数组转化为字符串形式并输出。
    程序示例:
    [java] view plain copy
     
    1. package captain;  
    2.   
    3. import java.util.Arrays;  
    4.   
    5. public class ArrayDemo3 {  
    6.   
    7.     public static void main(String[] args) {  
    8.         // TODO Auto-generated method stub  
    9.           
    10.         //Arrays工具类的toString静态方法遍历二维数组。  
    11.         int arr[][] = new int[][]{{9,8},{7,6,5}};  
    12.         for(int i = 0; i < arr.length; i++){//循环得到一维数组  
    13.             System.out.println(Arrays.toString(arr[i]));//将一维数组转化为字符串输出  
    14.         }  
    15.     }  
    16.   
    17. }  
  • 相关阅读:
    针对上一篇文章中的代码,想出的重构方案(python实现)
    Android中的广播Broadcast详解
    Android中的Serialable和Parcelable的区别
    Java中的序列化Serialable高级详解
    Android中的Parcel机制(下)
    Android中的Parcel机制(上)
    Java中获取前一天和后一天时间
    Android中的Service详解
    Window 通过cmd查看端口占用、相应进程、杀死进程等的命令
    Java高新技术第三篇:注解的使用
  • 原文地址:https://www.cnblogs.com/guoziyi/p/7154030.html
Copyright © 2011-2022 走看看