Learn Java - Chapter 1 變量(Variables)-數組(Arrays)

Java數組在被建立的時候肯定數組長度。索引下標從0開始。html

Illustration of an array as 10 boxes numbered 0 through 9; an index of 0 indicates the first element in the array

1.數組定義及初始化java

int[] anArray;//定義
anArray = new int[2];//初始化
anArray[0] = 100;//賦值
anArray[1] = 200;//賦值
  
System.out.println("Element at index 0: " + anArray[0]);//使用
System.out.println("Element at index 1: " + anArray[1]);//使用

程序輸出:api

Element at index 0: 100
Element at index 1: 200

2.定義初始化同時賦值數組

int[] anArray = { 
    100, 200, 300,
    400, 500, 600, 
    700, 800, 900, 1000
};

3.多維數組
oracle

String[][] names = {
    {"Mr. ", "Mrs. ", "Ms. "},
    {"Smith", "Jones"}
};
System.out.println(names[0][0] + names[1][0]);
System.out.println(names[0][2] + names[1][1]);

程序輸出:工具

Mr. Smith
Ms. Jones

從以上例子中能夠看出,Java多維數組每一行數組的長度不要求相等。spa

4.複製數組code

    

class ArrayCopyDemo {
    public static void main(String[] args) {
        char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e',
			    'i', 'n', 'a', 't', 'e', 'd' };
        char[] copyTo = new char[7];

        System.arraycopy(copyFrom, 2, copyTo, 0, 7);
        System.out.println(new String(copyTo));
    }
}

程序輸出:htm

caffein

5.Arrays工具類對象

Java SE提供了java.util.Arrays工具類操做數組,經常使用的方法有:

搜索:binarySearch 

比較:equals 

填充:fill 

排序:sort (sort 自定義類時,能夠根據業務重寫業務對象的sort方法來實現業務排序),Java 8還新添了方法parallelSort來進行數組的並行排序。

相關文章
相關標籤/搜索