16.2 数组是第一级对象
ArrayOptions
class BerylliumSphere {
private static long counter;
private final long id = counter++;
public String toString() {
return "Sphere:" + id;
}
}
class ArrayOptions {
public static void chapter16_2() {
//(1)对象数组
//(i)默认初始化
BerylliumSphere[] a = new BerylliumSphere[3];
System.out.println(Arrays.toString(a));
//(ii)列表初始化
BerylliumSphere[] b = new BerylliumSphere[] {new BerylliumSphere(),new BerylliumSphere()};
System.out.println(Arrays.toString(b));
//(2)基本数组
//(i)默认初始化
int[] c = new int[5];
System.out.println(Arrays.toString(c));
//(ii)列表初始化
int[] d = new int[5];
for(int i=0;i<5;i++){
d[i] = 7;
}
System.out.println(Arrays.toString(d));
}
}
对象数组保存的是引用,基本类型数组直接保存基本类型的值
16.3 返回一个数组
返回一个数组与返回其他对象(实际上返回引用)没什么区别。垃圾回收器会自动清理数组,不必操心。
16.4 多维数组
MultiArray
class MultiArray {
public static void chapter16_4() {
Integer[][] a = new Integer[3][];
for(int i=0;i<a.length;i++) {
a[i] = new Integer[5];
for(int j=0;j<a[i].length;j++) {
a[i][j] = i+j;
}
}
System.out.println(Arrays.deepToString(a));
}
}
Arrays.deepToString()可以将多维数组转换为多个String
16.7 Arrays实用功能
Arrays类一套用于数组的static实用方法:
equals 数组的比较
deepEquals 多维数组的比较
fill 填充数组
sort 数组排序
binarySearch 在已经排序的数组中查找元素
hashCode 产生数组散列码
Arrays.asList 接受任意的序列或数组作为其参数,并将其转变为List容器
CopyingArrays
class CopyingArrays {
public static void chapter16_7() {
int[] src = new int[] {1,2,3,4,5};
int[] dst = new int[10];
System.arraycopy(src,0,dst,0,src.length);
System.out.println(Arrays.toString(dst));
Integer[] a = new Integer[5];
Arrays.fill(a,7);
Integer[] b = new Integer[10];
System.arraycopy(a,0,b,5,a.length);
System.out.println(Arrays.toString(b));
a[4] = 11;
System.out.println(Arrays.toString(a));
System.out.println(Arrays.toString(b));
}
}
System.arraycopy(),用它复制数组比用for循环要快很多。
源数组,从源数组什么位置开始复制的偏移量,目标数组,从目标数组什么位置开始复制的偏移量,需要复制的元素个数
StringSorting
class StringSorting {
public static void chapter16_7() {
String[] str = new String[]{"Abcde","AAAAb","HxxHv","aaaaa"};
System.out.println(Arrays.toString(str));
Arrays.sort(str);
System.out.println(Arrays.toString(str));
int location = Arrays.binarySearch(str,"AAAAb");
System.out.println("location:" + location);
Arrays.sort(str,Collections.reverseOrder());
System.out.println(Arrays.toString(str));
//wrong
//location = Arrays.binarySearch(str,"AAAAb");
location = Arrays.binarySearch(str,"AAAAb", Collections.reverseOrder());
System.out.println("location:" + location);
Arrays.sort(str,String.CASE_INSENSITIVE_ORDER);
System.out.println(Arrays.toString(str));
location = Arrays.binarySearch(str,"AAAAb", String.CASE_INSENSITIVE_ORDER);
System.out.println("location:" + location);
}
}
数组排序:词典序,反词典序,忽略大小写词典序