• Java 資料結構教程

Java 資料結構 - 建立陣列



在 Java 中,陣列是一種資料結構/容器,它儲存相同型別元素的固定大小的順序集合。陣列用於儲存資料集合,但通常將陣列視為相同型別變數的集合更有用。

  • 元素 - 儲存在陣列中的每個專案稱為元素。

  • 索引 - 陣列中每個元素的位置都有一個數字索引,用於標識該元素。

建立陣列

要建立陣列,需要宣告特定陣列,方法是指定其型別和引用它的變數。然後,使用 new 運算子為已宣告的陣列分配記憶體(在方括號“[ ]”中指定陣列的大小)。

語法

dataType[] arrayRefVar;   
arrayRefVar = new dataType[arraySize];
(or)
dataType[] arrayRefVar = new dataType[arraySize];

或者,可以透過直接指定用逗號分隔的元素(在大括號“{ }”內)來建立陣列。

dataType[] arrayRefVar = {value0, value1, ..., valuek};

透過索引訪問陣列元素。陣列索引從 0 開始;也就是說,它們從 0 到 arrayRefVar.length-1。

示例

以下語句宣告一個整數型別的陣列變數 myArray,並分配記憶體以儲存 10 個整數型別元素,並將它的引用賦值給 myArray。

int[] myList = new int[10];

填充陣列

上述語句只是建立了一個空陣列。需要透過使用索引為每個位置賦值來填充此陣列 -

myList [0] = 1;
myList [1] = 10;
myList [2] = 20;
.
.
.
.

示例

以下是建立整數的 Java 示例。在此示例中,我們嘗試建立一個大小為 10 的整數陣列,填充它,並使用迴圈顯示其內容。

public class CreatingArray {
   public static void main(String args[]) {
      int[] myArray = new int[10];
      myArray[0] = 1;
      myArray[1] = 10;
      myArray[2] = 20;
      myArray[3] = 30;
      myArray[4] = 40;
      myArray[5] = 50;
      myArray[6] = 60;
      myArray[7] = 70;
      myArray[8] = 80;
      myArray[9] = 90;      
      System.out.println("Contents of the array ::");
      
      for(int i = 0; i<myArray.length; i++) {
        System.out.println("Element at the index "+i+" ::"+myArray[i]);
      } 
   }
}

輸出

Contents of the array ::
Element at the index 0 ::1
Element at the index 1 ::10
Element at the index 2 ::20
Element at the index 3 ::30
Element at the index 4 ::40
Element at the index 5 ::50
Element at the index 6 ::60
Element at the index 7 ::70
Element at the index 8 ::80
Element at the index 9 ::90

示例

以下是另一個 Java 示例,它透過獲取使用者的輸入來建立和填充陣列。

import java.util.Scanner;
public class CreatingArray {
   public static void main(String args[]) {
      // Instantiating the Scanner class
      Scanner sc = new Scanner(System.in);
      
      // Taking the size from user
      System.out.println("Enter the size of the array ::");
      int size = sc.nextInt();
      
      // creating an array of given size
      int[] myArray = new int[size];
      
      // Populating the array
      for(int i = 0 ;i<size; i++) {
         System.out.println("Enter the element at index "+i+" :");
         myArray[i] = sc.nextInt();
      }
      
      // Displaying the contents of the array
      System.out.println("Contents of the array ::");
      for(int i = 0; i<myArray.length; i++) {
         System.out.println("Element at the index "+i+" ::"+myArray[i]);
      }
   }
}

輸出

Enter the size of the array ::
5
Enter the element at index 0 :
25
Enter the element at index 1 :
65
Enter the element at index 2 :
78
Enter the element at index 3 :
66
Enter the element at index 4 :
54
Contents of the array ::
Element at the index 0 ::25
Element at the index 1 ::65
Element at the index 2 ::78
Element at the index 3 ::66
Element at the index 4 ::54
廣告
© . All rights reserved.