(1)如何創建空數組?int[] array = {};
int[] array = new int[]{};
如果是創建空集合呢?Collections 類有一個方法 emptyList(), 返回一個空 List,當然你可以直接 new 一個List也是一樣的,只是 emptyList() 方法返回的 List 是被 final 修飾的。
(2)如何對數組進行排序?
java.util.Arrays 類包含很多對數組進行操作的方法,如排序、搜索等,排序我們可以使用 Arrays.sort()方法,int[] array = {5, 3, 7, 1, 0, 88};
Arrays.sort(array);
這樣 array 就會從小到大排好序了,當然這個 sort 方法還可以對其他類型進行排序,詳情可以查閱文檔。
(3)如何提取數組的一部分生成另一個數組?
使用 Arrays.copyOfRange 方法,有三個參數,第一個是要提取的數組,第二個是從哪里開始,第三個是到哪里結束且不包括該位置。int[] array = {1, 2, 3, 4, 5};
int[] newArray = Arrays.copyOfRange(array, 0, 2);
newArray 就是 {1, 2},當然也可以自己寫個循環來賦值,想當於重新寫一個 copyOfRange 了。
(4)如何合並兩個數組,同時使合並的數組中不包含重復的元素?
這里的前提條件應該是這兩個數組本身不包含重復的元素。
暫時沒想到較好的寫法。
(5)如何在數組中用二分法搜索元素?
使用 Arrays.binarySearch 方法,int[] array = {1, 2, 3, 4, 5};
int position = Arrays.binarySearch(array, 3);
System.out.println(position);
上面代碼打印出 “2”, 就是 3 在數組 array 中的位置。注意傳入的數組必須是已經排好序的,不然結果會不准確,了解二分查找的應該都知道。如果沒有找到要找的元素,會返回什么呢?查閱文檔,可以看到
Returns: index of the search key, if it is contained in the array; otherwise, (-(insertion point) - 1). The insertion point is defined as the point at which the key would be inserted into the array: the index of the first element greater than the key, or a.length if all elements in the array are less than the specified key. Note that this guarantees that the return value will be >= 0 if and only if the key is found.
就是說如果沒有找到,就返回 (-(insertion point) - 1),這個 insertion 就是對於被搜索的數組來說,要查找的元素會被放置的位置。比如說你在 {1, 3, 5} 中查找 2 ,會返回 (-(1) - ),也就是 -2,這里的 insertion = 1,因為 2 會放置在第二個位置。
隨着 Java 版本的更新,越來越多的通用方法被加入進 jdk 里面,很多方法我們都不需要自己寫了,也就是不用重復造輪子了,當然我們還是需要去了解這個方法的實現原理,這樣我們才會有比較實際性的成長。
(6)如何將數組反轉?
我在文檔里貌似沒看到可以直接反轉的方法,所以就考慮自己寫一個吧,這里以 int 數組為例public void reverse(int[] array) {
int start = 0;
int end = array.length - 1;
while(start < end) {
int temp = array[start];
array[start] = array[end];
array[end] = temp;
start++;
end--;
}
}
就是通過循環將頭尾逐次交換。