<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                合規國際互聯網加速 OSASE為企業客戶提供高速穩定SD-WAN國際加速解決方案。 廣告
                # Java 中的數組 > 原文: [https://www.geeksforgeeks.org/arrays-in-java/](https://www.geeksforgeeks.org/arrays-in-java/) 數組是一組由通用名稱引用的相似類型的變量。Java 中的數組工作方式與 C/C++ 中的不同。 以下是有關 Java 數組的一些要點。 * 在 Java 中,所有數組都是動態分配的。(下面討論) * 由于數組是 Java 中的對象,因此我們可以使用成員長度來找到它們的長度。 這與 C/C++ 不同,在 C/C++ 中,我們使用`sizeof`查找長度。 * 像其他變量一樣,也可以在數據類型之后使用`[]`聲明 Java 數組變量。 * 數組中的變量是有序的,每個變量的索引都從 0 開始。 * Java 數組也可以用作靜態字段,局部變量或方法參數。 * 數組的**大小**必須由`int`值指定,且不能長或短。 * 數組類型的直接超類是[對象](https://www.geeksforgeeks.org/object-class-in-java/)。 * 每種數組類型都實現接口 [Cloneable](https://www.geeksforgeeks.org/marker-interface-java/) 和 [java.io.Serializable](https://www.geeksforgeeks.org/serialization-in-java/) 。 數組可以包含類的基元(`int`,`char`等)以及對象的對象(或非基元)引用,具體取決于數組的定義。 對于基元數據類型,實際值存儲在連續的存儲位置中。 對于[類的對象](https://www.geeksforgeeks.org/g-fact-46/),實際對象存儲在堆段中。 [![Arrays](https://img.kancloud.cn/cc/34/cc34b27af2f4e606c2ab6be72a8ea92c_592x173.png)](https://media.geeksforgeeks.org/wp-content/uploads/Arrays1.png) **創建,初始化和訪問數組** **一維數組**: 一維數組聲明的一般形式是 ``` type var-name[]; OR type[] var-name; ``` 數組聲明有兩個組成部分:類型和名稱。 *類型*聲明數組的元素類型。 元素類型確定組成數組的每個元素的數據類型。 像`int`類型的數組一樣,我們還可以創建其他原始數據類型的數組,例如`char`,`float`,`double`.. 等或用戶定義的數據類型(類的對象)。因此,數組的元素類型決定了哪種類型的 數組將保存的數據。 **例如**: ``` // both are valid declarations int intArray[]; or int[] intArray; byte byteArray[]; short shortsArray[]; boolean booleanArray[]; long longArray[]; float floatArray[]; double doubleArray[]; char charArray[]; // an array of references to objects of // the class MyClass (a class created by // user) MyClass myClassArray[]; Object[] ao, // array of Object Collection[] ca; // array of Collection // of unknown type ``` 盡管上述第一個聲明確定了`intArray`是一個數組變量的事實,但**實際上沒有數組**。 它只是告訴編譯器這個(`intArray`)變量將保存一個整數類型的數組。 要將`intArray`與實際的物理整數數組鏈接,必須使用新的**新**分配一個并將其分配給`intArray`。 **實例化 Java 中的數組** 聲明數組時,僅創建數組的引用。 要實際創建數組或為數組提供內存,您可以這樣創建一個數組: *new* 應用于一維數組的一般形式如下所示: ``` var-name = new type [size]; ``` 此處,*類型*指定要分配的數據類型,*大小*指定數組中元素的數量, *var-name* 是數組變量的名稱, 鏈接到數組。 也就是說,要使用*新的*分配數組,**必須指定要分配的元素的類型和數量。** **示例**: ``` int intArray[]; //declaring array intArray = new int[20]; // allocating memory to array ``` 要么 ``` int[] intArray = new int[20]; // combining both statements in one ``` **注意**: 1. 由*新*分配的數組中的元素將自動初始化為**零**(對于數字類型),**假**(對于布爾值)或 **null** (用于參考類型)。請參考 [Java](https://www.geeksforgeeks.org/default-array-values-in-java/) 中的默認數組值 2. 獲取數組是一個兩步過程。 首先,必須聲明所需數組類型的變量。 其次,您必須使用`new`分配用于保存數組的內存,并將其分配給數組變量。 因此,Java 中的**所有數組都是動態分配的**。 **數組文字** 在已知數組大小和數組變量的情況下,可以使用數組文字。 ``` int[] intArray = new int[]{ 1,2,3,4,5,6,7,8,9,10 }; // Declaring array literal ``` * 該數組的長度決定了所創建數組的長度。 * 無需在最新版本的 Java 中編寫新的`int[]`部分 **使用`for`循環**訪問 Java 數組元素 數組中的每個元素均通過其索引訪問。 索引以 0 開頭,以(總數組大小`- 1`) 結束。 可以使用 Java `for`循環訪問數組的所有元素。 ``` // accessing the elements of the specified array for (int i = 0; i < arr.length; i++) System.out.println("Element at index " + i + " : "+ arr[i]); ``` **實現**: ``` // Java program to illustrate creating an array // of integers,? puts some values in the array, // and prints each value to standard output. class GFG? { ????public static void main (String[] args)? ????{????????? ??????// declares an Array of integers. ??????int[] arr; ??????// allocating memory for 5 integers. ??????arr = new int[5]; ??????// initialize the first elements of the array ??????arr[0] = 10; ??????// initialize the second elements of the array ??????arr[1] = 20; ??????//so on... ??????arr[2] = 30; ??????arr[3] = 40; ??????arr[4] = 50; ??????// accessing the elements of the specified array ??????for (int i = 0; i < arr.length; i++) ?????????System.out.println("Element at index " + i +? ??????????????????????????????????????" : "+ arr[i]);?????????? ????} } ``` 輸出: ``` Element at index 0 : 10 Element at index 1 : 20 Element at index 2 : 30 Element at index 3 : 40 Element at index 4 : 50 ``` 您還可以使用[`foreach`循環](https://www.geeksforgeeks.org/for-each-loop-in-java/)訪問 Java 數組 ![Blank Diagram - Page 1 (10)](https://img.kancloud.cn/37/43/37434231aa6da99042dfa3d6a1c6064e_626x265.png) **對象數組** 對象數組的創建方式類似于原始類型數據項的數組,其創建方法如下。 ``` Student[] arr = new Student[7]; //student is a user-defined class ``` `studentArray`包含七個內存空間,每個內存空間可以容納七個學生類,每個學生類的大小可以存儲七個學生對象的地址。必須使用學生類的構造函數實例化學生對象,并且應將其引用分配給數組中的數組元素。 以下方式。 ``` Student[] arr = new Student[5]; ``` ``` // Java program to illustrate creating an array of // objects class Student { ????public int roll_no; ????public String name; ????Student(int roll_no, String name) ????{ ????????this.roll_no = roll_no; ????????this.name = name; ????} } // Elements of array are objects of a class Student. public class GFG { ????public static void main (String[] args) ????{ ????????// declares an Array of integers. ????????Student[] arr; ????????// allocating memory for 5 objects of type Student. ????????arr = new Student[5]; ????????// initialize the first elements of the array ????????arr[0] = new Student(1,"aman"); ????????// initialize the second elements of the array ????????arr[1] = new Student(2,"vaibhav"); ????????// so on... ????????arr[2] = new Student(3,"shikar"); ????????arr[3] = new Student(4,"dharmesh"); ????????arr[4] = new Student(5,"mohit"); ????????// accessing the elements of the specified array ????????for (int i = 0; i < arr.length; i++) ????????????System.out.println("Element at " + i + " : " + ????????????????????????arr[i].roll_no +" "+ arr[i].name); ????} } ``` Output: ``` Element at 0 : 1 aman Element at 1 : 2 vaibhav Element at 2 : 3 shikar Element at 3 : 4 dharmesh Element at 4 : 5 mohit ``` **如果我們嘗試訪問數組大小以外的元素會發生什么?** JVM 拋出`ArrayIndexOutOfBoundsException`,以指示已使用非法索引訪問了數組。 索引為負或大于或等于數組的大小。 ``` class GFG { ????public static void main (String[] args) ????{ ????????int[] arr = new int[2]; ????????arr[0] = 10; ????????arr[1] = 20; ????????for (int i = 0; i <= arr.length; i++) ????????????System.out.println(arr[i]); ????} } ``` 運行時錯誤 ``` Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2 at GFG.main(File.java:12) ``` Output: ``` 10 20 ``` **多維數組** 多維數組是數組的**數組,該數組的每個元素都包含其他數組的引用。 這些也稱為[鋸齒數組](https://www.geeksforgeeks.org/jagged-array-in-java/)。 通過在每個維上附加一組方括號([])來創建多維數組。 例子**: ``` int[][] intArray = new int[10][20]; //a 2D array or matrix int[][][] intArray = new int[10][20][10]; //a 3D array ``` ``` class multiDimensional { ????public static void main(String args[]) ????{ ????????// declaring and initializing 2D array ????????int arr[][] = { {2,7,9},{3,6,1},{7,4,2} }; ????????// printing 2D array ????????for (int i=0; i< 3 ; i++) ????????{ ????????????for (int j=0; j < 3 ; j++) ????????????????System.out.print(arr[i][j] + " "); ????????????System.out.println(); ????????} ????} } ``` Output: ``` 2 7 9 3 6 1 7 4 2 ``` ![Blank Diagram - Page 1 (13)](https://img.kancloud.cn/52/f9/52f9269099ec9403fed7b923404d0fc2_1105x426.png) **將數組傳遞給方法** 像變量一樣,我們也可以將數組傳遞給方法。例如,下面的程序將數組傳遞給方法 *sum* 以計算數組值的總和。 ``` // Java program to demonstrate? // passing of array to method class Test {???? ????// Driver method ????public static void main(String args[])? ????{ ????????int arr[] = {3, 1, 2, 5, 4}; ????????// passing array to method m1 ????????sum(arr); ????} ????public static void sum(int[] arr)? ????{ ????????// getting sum of array values ????????int sum = 0; ????????for (int i = 0; i < arr.length; i++) ????????????sum+=arr[i]; ????????System.out.println("sum of array values : " + sum); ????} } ``` 輸出: ``` sum of array values : 15 ``` **從方法**返回數組 和往常一樣,方法也可以返回數組。 例如,下面的程序從方法 *m1* 返回一個數組。 ``` // Java program to demonstrate? // return of array from method class Test {???? ????// Driver method ????public static void main(String args[])? ????{ ????????int arr[] = m1(); ????????for (int i = 0; i < arr.length; i++) ????????????System.out.print(arr[i]+" "); ????} ????public static int[] m1()? ????{ ????????// returning? array ????????return new int[]{1,2,3}; ????} } ``` Output: ``` 1 2 3 ``` **[類](https://www.geeksforgeeks.org/java-lang-class-class-java-set-1/)數組的對象** 每個數組都有一個關聯的[類](https://www.geeksforgeeks.org/java-lang-class-class-java-set-1/)對象,該對象與具有相同組件類型的所有其他數組共享。 ``` // Java program to demonstrate? // Class Objects for Arrays class Test {? ????public static void main(String args[])? ????{ ????????int intArray[] = new int[3]; ????????byte byteArray[] = new byte[3]; ????????short shortsArray[] = new short[3]; ????????// array of Strings ????????String[] strArray = new String[3]; ????????System.out.println(intArray.getClass()); ????????System.out.println(intArray.getClass().getSuperclass()); ????????System.out.println(byteArray.getClass()); ????????System.out.println(shortsArray.getClass()); ????????System.out.println(strArray.getClass()); ????} } ``` Output: ``` class [I class java.lang.Object class [B class [S class [Ljava.lang.String; ``` **說明**: 1. 字符串“`I`”是類對象“組件類型為`int`的數組”的運行時類型簽名。 2. 任何數組類型的唯一直接超類是[`java.lang.Object`](https://www.geeksforgeeks.org/object-class-in-java/)。 3. 字符串“`B`”是類對象“組件類型為*字節*”的數組的運行時類型簽名。 4. 字符串“`S`”是類對象“組件類型為*短為*的數組”的運行時類型簽名。 5. 字符串“`L`”是類對象“具有類的組件類型的數組”的運行時類型簽名。 然后跟隨類名。 **數組成員** 現在您知道數組是類的對象,數組的直接超類是類[對象](https://www.geeksforgeeks.org/object-class-in-java/)。數組類型的成員如下: * 公共最終字段*長度*,其中包含數組的組件數。 *長度*可以為正或為零。 * 從類[`Object`繼承的所有成員;](https://www.geeksforgeeks.org/object-class-in-java/) 對象的唯一方法是[克隆](https://www.geeksforgeeks.org/clone-method-in-java-2/)方法。 * 公共方法`clone()`,它重寫類`Object`中的克隆方法,并且不拋出[檢查的異常](https://www.geeksforgeeks.org/checked-vs-unchecked-exceptions-in-java/)。 **克隆數組** * When you clone a single dimensional array, such as Object[], a “deep copy” is performed with the new array containing copies of the original array’s elements as opposed to references. ``` // Java program to demonstrate? // cloning of one-dimensional arrays class Test {???? ????public static void main(String args[])? ????{ ????????int intArray[] = {1,2,3}; ????????int cloneArray[] = intArray.clone(); ????????// will print false as deep copy is created ????????// for one-dimensional array ????????System.out.println(intArray == cloneArray); ????????for (int i = 0; i < cloneArray.length; i++) { ????????????System.out.print(cloneArray[i]+" "); ????????} ????} } ``` Output: ``` false 1 2 3 ``` ![Blank Diagram - Page 1 (11)](https://img.kancloud.cn/46/ee/46ee3dbf4ac40460c98e927461ca0e87_702x552.png) * A clone of a multidimensional array (like Object[][]) is a “shallow copy” however, which is to say that it creates only a single new array with each element array a reference to an original element array but subarrays are shared. ``` // Java program to demonstrate? // cloning of multi-dimensional arrays class Test {???? ????public static void main(String args[])? ????{ ????????int intArray[][] = {{1,2,3},{4,5}}; ????????int cloneArray[][] = intArray.clone(); ????????// will print false ????????System.out.println(intArray == cloneArray); ????????// will print true as shallow copy is created ????????// i.e. sub-arrays are shared ????????System.out.println(intArray[0] == cloneArray[0]); ????????System.out.println(intArray[1] == cloneArray[1]); ????} } ``` Output: ``` false true true ``` ![Blank Diagram - Page 1 (12)](https://img.kancloud.cn/47/4c/474c242dfd401b7606e492dbe36680d8_1209x603.png) **相關文章**: [Java 中的鋸齒數組](https://www.geeksforgeeks.org/jagged-array-in-java/) [Java 中的`For-each`循環](https://www.geeksforgeeks.org/for-each-loop-in-java/) [Java 中的數組類](https://www.geeksforgeeks.org/array-class-in-java/) **參考**:Oracle 的[數組](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html)
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看