java數組的聲明、創建和遍歷


一、數組的聲明、創建

1、一維數組

先是聲明

dataType[] arrayRefVar; // 首選的方法

數據類型[] 數組名;

dataType arrayRefVar[]; // 效果相同,但不是首選方法

數據類型 數組名[];

創建

(1)

arrayRefVar = new dataType[arraySize];

數組名 = new 數據類型[數組大小];

(2)

  dataType[] arrayRefVar = new dataType[arraySize];
  數據類型[] 數組名 = new 數據類型[數組大小];
  (3)
  dataType[] arrayRefVar = {value0,value1, ..., valuek};
  數據類型[] 數組名 = {值1,值2······}

 另外,數組大小可以用:數組名.length 表示。

2、二維數組

聲明

和一維數組差不多,多個[]。

創建

type[][] typeName = new type[typeLength1][typeLength2];
數據類型[][] 數組名 = new 數據類型[長度1][長度2];
(1)直接為每一維分配空間
二維數組可以看成是一個行列式,比如 int a[][] = new int[2][3]; 二維數組 a 是一個兩行三列的數組。
(2)從最高維開始,分別為每一維分配空間
String s[][] = new String[2][];
s[0] = new String[2];
s[1] = new String[3];
s[0][0] = new String("Good");
s[0][1] = new String("Luck");
s[1][0] = new String("to");
s[1][1] = new String("you");
s[1][2] = new String("!");

s[0]=new String[2]s[1]=new String[3] 是為最高維分配引用空間,也就是為最高維限制其能保存數據的最長的長度,然后再為其每個數組元素單獨分配空間 s0=new String("Good") 等操作。這時二維數組就不能看成是行列式了。


 

二、數組遍歷

 (1)for循環

一維數組:

public class TestArray {
   public static void main(String[] args) {
      double[] myList = {1.9, 2.9, 3.4, 3.5};
 
      // 打印所有數組元素
      for (int i = 0; i < myList.length; i++) {
         System.out.println(myList[i] + " ");
      }
}

   二維數組:

public class Test{
    public static void main(string[] args) {
        int[][] myList = {(1,2,3),(4,5),(6)};
        for(int i = 0; i < myList.length ;i++) {
            for(int j = 0; j < myList.length ;j++) {
                system.out.println(myList[i][j] + " ");
                    }
                }
        }
}

 (2)for-each循環

 一維數組:

public class TestArray {
   public static void main(String[] args) {
      double[] myList = {1.9, 2.9, 3.4, 3.5};
 
      // 打印所有數組元素
      for (double element: myList) {
         System.out.println(element);
      }
   }
}

 二維數組:

public class Test{
    public static void main(String[] args) {
        int[][] arr = {(1,2,3),(4,5),(6)};
            for(int[] x; arr) {
                for(int y; x) {
                    system.out.println(y + " ");
                    }
                }
            }
    }
  • for-each循環只能用來遍歷,無法在遍歷的過程中對數組或者集合進行修改。
  • foreach不是java中的關鍵字。

取材於菜鳥教程和百度百科。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM