1. 程式人生 > >java基礎複習(陣列)

java基礎複習(陣列)

  • 陣列宣告:
int[] a, b;  // Both a and b are arrays of type int
int c[], d;  // WARNING: c is an array, but d is just a regular int
  • 陣列初始化initialize:

An array initializer creates an array and provides initial values for all its components.

//初始化的值為:
For references (anything that holds an object) that is null
. For int/short/byte/long that is a 0. For float/double that is a 0.0 For booleans that is a false. For char that is the null character '\u0000' (whose decimal equivalent is 0).
  • 一句話宣告、初始化陣列
//注意,不能分開寫
int[] array1 = {1, 2, 3, 4, 5, 6, ,7, 8}; - working

//錯誤示範
int[] array1;
array1 = {1, 1, 1, 1, 2, 5, ,7
, 8}; - NOT working //應改成 array = new int[] {1, 1, 2, 3, 5, 8};

陣列一旦建立,大小就確定了
可以用arr.length 獲得陣列長度

  • 增強型for迴圈 foreach
for (elementType value: arrayRefVar) {
  // 語句
 }

需要注意的問題:
在foreach迴圈中不要去刪除元素!
正確的寫法應該是:

List<String> names = ....
Iterator<String> i = names.iterator();
while
(i.hasNext()) { String s = i.next(); // must be called before you can call i.remove() // Do something i.remove(); } //!! //Note that the code calls Iterator.remove, not List.remove.

若想在迴圈中刪除元素,則應該使用iterator,因為foreach是語法糖,內部是使用迭代器實現的,但對外隱藏了iterator的細節。我們並不知道一個collection內部實現,所以在foreach中刪除元素,可能導致意想不到的錯誤
It can cause undefined behavior depending on the collection. You want to use an Iterator directly. Although the for each construct is syntactic sugar and is really using an iterator, it hides it from your code so you can’t access it to call Iterator.remove.
The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method.

  • 陣列的複製

1、通過迴圈語句實現
2、System.arraycopy

int[] src  = new int[]{1,2,3,4,5};
int[] dest = new int[5];

System.arraycopy( src, 0, dest, 0, src.length );

3、Arrays.copyOf(比clone快)

int[] a = {1,2,3,4,5};
int[] b = Arrays.copyOf(a, a.length);

4、clone

int[] a = new int[]{1,2,3,4,5};
int[] b = a.clone();
  • 二維陣列

二維陣列的建立
1、int[][] multi = new int[5][10];(是2的簡便寫法)
2、

int[][] multi = new int[5][];
multi[0] = new int[10];
multi[1] = new int[10];
multi[2] = new int[10];
multi[3] = new int[10];
multi[4] = new int[10];

//以上等價於
int[][] multi = new int[][]{
  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
};

二維陣列的維度
行:arr.length
列:arr[i].length

int nir[][] = new int[5][];
nir[0] = new int[5];
nir[1] = new int[3];
System.out.println(nir[0].length); // 5
System.out.println(nir[1].length); // 3
System.out.println(nir[2].length); // Null pointer exception