Arrays类概述
数组操作工具类,专门用于操作数组元素的。
Arrays类的常用API
| 方法名 | 说明 |
|---|---|
| public static String toString(类型[] a) | 对数组进行输出 |
| public static void sort(类型[] a) | 对数组进行默认升序排序 |
| public static <T> void sort(类型[] a, Comparator<? super T> c) | 使用比较器对象自定义排序 |
| public static int binarySearch(int[] a, int key) | 二分搜索数组中的数据,存在返回索引,不存在返回-1 |
二分查找如果结果不存在,会返回负数:-(应该插入位置的索引+1)
Arrays类的排序方法
自定义排序规则
设置Comparator接☐对应的比较器对象,来定制比较规则。
升序:如果认为左边数据 大于 右边数据 返回正整数如果认为左边数据 小于 右边数据 返回负整数如果认为左边数据 等于右边数据 返回0
降序排序
Integer [] ages1 = {34,12,42,23};
Arrays.sort(ages1,new Comparator<Integer>(){
@override
public int compare(Integer o1,Integer o2){
return o2 - o1;
}
});
System.out.println(Arrays.tostring(ages1));
类中的排序
Student[] students = new student[3];
students[0] = new Student(张三,22);
students[1] = new Student(李四,20);
students[2] = new Student(王二,23);
Arrays.sort(students,new Comparator<Integer>(){
@override
public int compare(Student o1,Student o2){
return o1.getAge() - o2.getAge();//按年龄升序排序
}
});
System.out.println(Arrays.tostring(ages1));
如果是小数排序
可以使用return Double.compare(o1.getHeight(),o2.getHeight());