陣列入門

Java 入門

Jim White

Java Developer

Array 是什麼?

陣列是以單一變數儲存的一組值

Java 入門

Array 就像一排置物櫃!

陣列像是一排置物櫃,每個櫃子都有編號標籤(索引)

Java 入門

宣告與填入陣列

  • 使用方括號 []
// Declare array variable
int[] prices;

// Assign value prices = {10, 20, 30, 40};

數值 10、20、30、40 依序放在第 1、2、3、4 號置物櫃

Java 入門

存取元素

  • 使用 []
int[] prices = {10, 20, 30, 40};

// Accessing first element
int firstElement = prices[0]; // Value is 10

// Accessing second element
int secondElement = prices[1]; // Value is 20

Java 的索引從 0 開始

Java 入門

變更元素的值

  • 指定索引重新指派即可改值
int[] prices = {10, 20, 30, 40};

// 將第 3 個元素改為 95 prices[2] = 95;

5_Ch2_L4_.jpg

Java 入門

陣列長度是固定的

  • 陣列長度在建立時就固定
int[] itemIDs = {10, 20, 30, 40, 50};

// 存取不存在的第六個元素
itemIDs[5] = 60; // <- 這會造成錯誤
  • .length 屬性查看長度
int[] prices = {10, 20, 30, 40};

int pricesLength = prices.length; // Value is 4

對陣列取 .length 不需任何括號

Java 入門

列印元素值

你可以個別列印元素:

class ArrayElementPrinting {
  public static void main (String[] args){
    int[] prices = {10, 20, 30, 40};

    // Printing element by element
    System.out.println(prices[0]);
    System.out.println(prices[1]);
  }
}
10
20
Java 入門

嘗試列印整個陣列

直接列印整個陣列會得到其表示法:

class ArrayPrinting {
  public static void main (String[] args){
    int[] prices = {10, 20, 30, 40};

    // Printing whole thing
    System.out.println(prices);
  }
}
[I@d041cf
Java 入門

不同型別的陣列

// Array of Strings
String[] productNames = {"Organic Honey", 
                         "Cold Brew Coffee", 
                         "Dark Chocolate Bar"};
Java 入門

陣列中的值

  • 不僅能放數字或 Strings

陣列中的所有值必須同一型別

Java 入門

重點回顧

  • 陣列可儲存多個「同型別」的值
  • 陣列索引從 0 開始
  • 陣列長度固定
// Declare and assign
int[] prices = {10, 20, 30, 40};

// Retrieve
int secondElement = prices[1];

// Update
prices[1] = 25;

// Length
// Value is 4
int pricesLength = prices.length; 
Java 入門

一起來練習吧!

Java 入門

Preparing Video For Download...