java.util.Arrays有一套用于數(shù)組的static實用方法。
equals():比較兩個數(shù)組是否相等,兩個數(shù)組內(nèi)容相同,且數(shù)組大小也相同才返回true。
fill():用一個值填充數(shù)組。
sort():對數(shù)組進行排序, 基本類型用快速排序,針對對象用穩(wěn)定歸并排序。
binarySearch():在排好序中的數(shù)組中進行二分查找,找到元素則返回元素的索引,否則返回負(fù)數(shù)。數(shù)組中若包含重復(fù)元素,無法確保找到的是哪一個。
asList():由數(shù)組得到一個list, 但是這個List的實現(xiàn)類是java.util.Arrays.ArrayList這個類(而不是java.util.ArrayList),它的內(nèi)部保存了數(shù)組的引用,修改了數(shù)組的值,list的值也會改變。對list做add、remove操作會拋出UnsupportedOperationException異常, 因為它本質(zhì)還是一個大小不可變的數(shù)組。
System.arraycopy():比for循環(huán)更高效的數(shù)組復(fù)制方法,它是淺拷貝,如果復(fù)制對象數(shù)組,只會復(fù)制對象的引用。
對于元素不是基本類型的對象,用equals()和sort()方法時,需重寫元素的equals()方法和實現(xiàn)Comparable接口。
import
java.util.Arrays;
import
java.util.List;
public
class
ArraySDemo {
public
static
void
main(String[] args) {
Integer[] a = {
11
,
9
,
2
,
5
,
8
,
0
,
6
};
Integer[] b = {
15
,
8
,
45
,
62
,
12
,
3
,
10
,
8
};
Integer[] c =
new
Integer[
10
];
Integer[] d =
new
Integer[a.length];
System.arraycopy(a,
0
, d,
0
, a.length);
System.out.println(Arrays.equals(a, d));
System.arraycopy(a,
0
, c,
0
, a.length);
List<Integer> list = Arrays.asList(c);
// list.add(1); 不能增加或刪除元素,因為它內(nèi)部是數(shù)組會拋異常
System.out.println(list);
System.arraycopy(b,
0
, c,
0
, b.length);
System.out.println(list);
// 數(shù)組的內(nèi)容改變了,因為asList()方法,只是保存了數(shù)組的引用
int
[] a1 = {
11
,
9
,
2
,
5
,
8
,
0
,
6
};
int
[] b1 = {
15
,
8
,
45
,
62
,
12
,
3
,
10
,
8
};
int
[] c1 =
new
int
[
30
];
int
[] d1 =
new
int
[a1.length];
System.arraycopy(a1,
0
, c1,
0
, a1.length);
// a1和c1長度不同
System.out.println(Arrays.equals(a1, c1));
// false
System.arraycopy(a1,
0
, d1,
0
, a1.length);
// 長度相同,對應(yīng)元素也相同
System.out.println(Arrays.equals(a1, d1));
// true
System.out.println(Arrays.equals(a1, a1.clone()));
Arrays.sort(a1);
System.out.println(Arrays.equals(a1, d1));
// 排序后不同了 false
}
}
輸出結(jié)果:true[11, 9, 2, 5, 8, 0, 6, null, null, null][15, 8, 45, 62, 12, 3, 10, 8, null, null]falsetruetruefalse