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. }  
  • 相关阅读:
    STL源码剖析之_allocate函数
    PAT 1018. Public Bike Management
    PAT 1016. Phone Bills
    PAT 1012. The Best Rank
    PAT 1014. Waiting in Line
    PAT 1026. Table Tennis
    PAT 1017. Queueing at Bank
    STL源码剖析之list的sort函数实现
    吃到鸡蛋好吃,看看是哪只母鸡下的蛋:好用的Sqlite3
    cJSON
  • 原文地址:https://www.cnblogs.com/guoziyi/p/7154030.html
Copyright © 2011-2022 走看看