4.1 元素排序/查找元素位置 Arrays.sort、Arrays.binarySearch
public static void main(String args[]) throws Exception {
int array[] = { 2, 5, -2, 6, -3, 8, 0, -7, -9, 4 };
Arrays.sort(array);
printArray("数组排序结果为", array); // -9, -7, -3, -2, 0, 2, 4, 5, 6, 8
int index = Arrays.binarySearch(array, 2);
System.out.println("元素 2 在第 " + index + " 个位置");
}
4.2 获取最大值和最小值 Collections 工具类
Integer[] numbers = { 8, 2, 7, 1, 4, 9, 5};
int min = (int) Collections.min(Arrays.asList(numbers));
int max = (int) Collections.max(Arrays.asList(numbers));
4.3 数组合并 Arrays.asList、addAll
public class Main {
public static void main(String args[]) {
String a[] = { "A", "E", "I" };
String b[] = { "O", "U" };
List list = new ArrayList(Arrays.asList(a));
list.addAll(Arrays.asList(b));
Object[] c = list.toArray();
System.out.println(Arrays.toString(c));
}
}
4.4 数组填充 Arrays.fill
public class FillTest {
public static void main(String args[]) {
int array[] = new int[6];
Arrays.fill(array, 100); // 100, 100, 100, 100, 100, 100
for (int i=0, n=array.length; i < n; i++) {
System.out.println(array[i]);
}
System.out.println();
Arrays.fill(array, 3, 6, 50); // 100, 100, 100, 50, 50, 50
for (int i=0, n=array.length; i< n; i++) {
System.out.println(array[i]);
}
}
}
4.5 数组扩容/复制 System.arraycopy
String[] names = new String[] { "A", "B", "C" };
String[] extended = new String[5];
System.arraycopy(names, 0, extended, 0, names.length); // A, B, C, NULL, NULL
4.6 数组交集 retainAll
public class Main {
public static void main(String[] args) {
ArrayList objArray = new ArrayList(); ArrayList objArray2 = new ArrayList();
objArray2.add(0,"common1"); objArray2.add(1,"common2"); objArray2.add(2,"notcommon");
objArray2.add(3,"notcommon1"); objArray.add(0,"common1"); objArray.add(1,"common2"); objArray.add(2,"notcommon2");
System.out.println("array1 数组元素:"+objArray); // [common1, common2, notcommon2]
System.out.println("array2 数组元素:"+objArray2); // [common1, common2, notcommon, notcommon1]
objArray.retainAll(objArray2);
System.out.println("array2 & array1 数组交集为:"+objArray); // [common1, common2]
}
}
4.7 数组差集 removeAll
public class Main {
public static void main(String[] args) {
ArrayList objArray = new ArrayList(); ArrayList objArray2 = new ArrayList();
objArray2.add(0,"common1"); objArray2.add(1,"common2"); objArray2.add(2,"notcommon");
objArray2.add(3,"notcommon1"); objArray.add(0,"common1"); objArray.add(1,"common2"); objArray.add(2,"notcommon2");
System.out.println("array1 数组元素:"+objArray); // [common1, common2, notcommon2]
System.out.println("array2 数组元素:"+objArray2); // [common1, common2, notcommon, notcommon1]
objArray.removeAll(objArray2);
System.out.println("array1 与 array2 数组差集为:"+objArray); // [notcommon2]
}
}
4.8 查找元素是否存在 contains
ArrayList<String> objArray = new ArrayList<String>();
objArray.add(0,"common1"); objArray.add(1,"common2");
objArray.contains("common2"); // true
4.9 数组比较 Arrays.equals
int[] ary = {1,2,3,4,5,6}; int[] ary1 = {1,2,3,4,5,6};
Arrays.equals(ary, ary1); // true