天天看點

《Java程式設計技巧1001條》 第380條: 數組的索引

《Java程式設計技巧1001條》 第380條: 數組的索引

《Java程式設計技巧1001條》

第10部分 使用數組存儲資料

第380條 為數組索引

380 Understanding Array Indexing

380 了解數組的下标記法

Each valueof an array is called an array element. To access an array element, you specifythe name of the array with the index of that element placed betweenbracketbraces []. Java array indexing is similar to that of C/C++. Thefollowing code demonstrates a loop that cycles through all the elements of anarray and displays each value to the screen:

數組中的每一個資料叫數組元素. 要存取一個數組的元素,你應指出該數組的名字,并在其後面的一對括号中填入所需元素的索引号(即下标). Java數組的下标形式和C或C++是類似的. 以下語句是一個循環程式,它依次引用一個數組中的每一個元素,并在螢幕上顯示了每一個元素的值:

int myarray[] = { 1, 2, 3, 4, 5 };

for (int index = 0; index < 5; index++)

 {

  System.println(myarray[index]);

 }

In thisexample, the size of the array is five. In Java, the index of the first elementof an array is zero, and the last location is the size of the array minus one.Therefore, to loop through all the members of the array, the program uses theloop variable values 0 to 4. When you index a Java array, Java checks that theindex value is greater than or equal to zero and less than the size of thearray. If the index is less than zero or greater than or equal to the size ofthe arrayout of thisrange, then Java will generate anIndexOutOfBoundsException  error andterminate your program. (An exceptions is how Java flags an error conditions.You will learn about the exceptions in later tips. )

在這一例子中,數組的大小是5. 在Java中,數組的第一個元素的下标為0,而最後一個元素的下标是數組的大小減1. 是以,循環要通過所有元素,程式循環變量的取值應是0到4.

當你用下标引用Java數組時,Java将檢查所用下标是否大于,小于或等于數組的大小.如果下标小于0,或大于或等于數組的尺寸,則Java将産生一個訓示下标已溢出數組範圍的錯誤:IndexOutOfBoundsException,并終止你的程式.Exception(例外)是Java用于說明各種出錯情況的标志. 你在今後的一些TIP中會學到有關的各種Exception.