Arrays用法整理
Arrays用法整理
bharals 发表于9个月前
Arrays用法整理
• 发表于 9个月前
• 阅读 6
• 收藏 1
• 评论 0

# 原文

1.  asList方法
``````@SafeVarargs
public static <T> List<T> asList(T... a) {
return new ArrayList<>(a);
}``````
使用该方法可以返回一个固定大小的List，如：
``````List<String> stringList = Arrays.asList("Welcome", "To", "Java",
"World!");

List<Integer> intList = Arrays.asList(1, 2, 3, 4);``````

2. binarySearch方法

binarySearch方法支持在整个数组中查找，如：
``int index = Arrays.binarySearch(new int[] { 1, 2, 3, 4, 5, 6, 7 }, 6);``

``````public static int binarySearch(int[] a, int fromIndex, int toIndex,
int key) {
rangeCheck(a.length, fromIndex, toIndex);
return binarySearch0(a, fromIndex, toIndex, key);
}``````
``int index = Arrays.binarySearch(new int[] { 1, 2, 3, 4, 5, 6, 7 }, 1, 6, 6);``
3. copyOf及copyOfRange方法

``````String[] names2 = { "Eric", "John", "Alan", "Liz" };

//[Eric, John, Alan]
String[] copy = Arrays.copyOf(names2, 3);

//[Alan, Liz]
String[] rangeCopy = Arrays.copyOfRange(names2, 2,
names2.length);``````
4. sort方法
``````String[] names = { "Liz", "John", "Eric", "Alan" };
//只排序前两个
//[John, Liz, Eric, Alan]
Arrays.sort(names, 0, 2);
//全部排序
//[Alan, Eric, John, Liz]
Arrays.sort(names);``````

``public static <T> void sort(T[] a, Comparator<? super T> c) { if (LegacyMergeSort.userRequested) legacyMergeSort(a, c); else TimSort.sort(a, c); }``
5. toString方法
Arrays的toString方法可以方便我们打印出数组内容。

``````String[] names = { "Liz", "John", "Eric", "Alan" };
Arrays.sort(names);
System.out.println(Arrays.toString(names));``````

6. deepToString方法

int[][] stuGrades = { { 80, 81, 82 }, { 84, 85, 86 }, { 87, 88, 89 } };

``System.out.println(Arrays.toString(stuGrades));``

[[I@35ce36, [I@757aef, [I@d9f9c3]}

``System.out.println(Arrays.deepToString(stuGrades));``
7. equals方法

``````String[] names1 = { "Eric", "John", "Alan", "Liz" };

String[] names2 = { "Eric", "John", "Alan", "Liz" };

System.out.println(Arrays.equals(names1, names2));``````
8. deepEquals方法
Arrays.deepEquals能够去判断更加复杂的数组是否相等。
``````int[][] stuGrades1 = { { 80, 81, 82 }, { 84, 85, 86 }, { 87, 88, 89 } };

int[][] stuGrades2 = { { 80, 81, 82 }, { 84, 85, 86 }, { 87, 88, 89 } };

9. fill方法
``````int[] array1 = new int[8];
Arrays.fill(array1, 1);
//[1, 1, 1, 1, 1, 1, 1, 1]
System.out.println(Arrays.toString(array1));``````

×