Arrays类
包含了一些静态方法,用来管理和操作数组(比如排序和索引)
class test{
//Arrays的常用方法
//stor排序
//有两种排序方法,一时默认排序,一种是定制排序
Integer[] arr = {0, -1, 8, 3, 2};
//默认排序
Arrays.stor(arr);//默认从小到大排序
System.out.println(arr);//这里输出[-1, 0, 2, 3, 8]
//定制排序
Arrys.stor(arr, new Compparator<Integer>(){//这里用到了匿名内部类
@Override
public int compare(Integer o1, Integer o2){
return o1 - o2;//从小到大排序
//return o2 - o1;从大到小排序
}
})
}
模拟定制排序
class test {
public static void main(String[] args) {
int[] i = {0,-1,23,5,3,6};
test.pandua(i, new Comparator() {
@Override
public int compare(Object o1, Object o2) {
int i1 = (int) o1;
int i2 = (int) o2;
return i2 - i1;
}
});
System.out.println(Arrays.toString(i));
}
public static void pandua(int[] arr, Comparator c){
for (int i = 0; i < arr.length - 1; i++) {
for (int j = 0; j < arr.length - 1 - i; j++) {
if(c.compare(arr[j] ,arr[j+1]) > 0){
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
}
binarySearch() 二分查找
class test{
int[] i = {0,1,2,4,5};
//二分查找,必须是有序数列,不能是无序的
int index = Arrays.binarySearch(i,2);
System.out.println(index);//这里输出2
//如果数组不存在该元素则返回,这个值应该在的位置+1去负数
//例:找3,但是数组中不存在,3应该在的位置是3,所以,返回-(3+1)=-4
}