Arrays是用来操作数组的一个工具类
import java.util.Arrays;
import java.util.Comparator;
import java.util.function.IntToDoubleFunction;
public class Test {
public static void main(String[] args) {
//1.以字符串形式返回数组的内容
int[] arr = {10,20,30,40,50,60};
System.out.println(Arrays.toString(arr));
//2.拷贝数组(指定范围) 包前不包后
int[] arr2 = Arrays.copyOfRange(arr,1,4);
System.out.println(Arrays.toString(arr2)); //20 30 40
//3.拷贝数组,可以指定新数组的长度
int[] arr3 = Arrays.copyOf(arr,10); //空位默认0
System.out.println(Arrays.toString(arr3)); //10,20,30,40,50,60,0,0,0,0
//4.把数组中的原数据改为新数据存进去
double[] b = {99.1,10.2,444};
//把所有的数乘以2再存进去
Arrays.setAll(b, new IntToDoubleFunction() { //匿名内部类
@Override
public double applyAsDouble(int value) {
//value = 0 1 2 3
return b[value]*2;
}
});
System.out.println(Arrays.toString(b)); //[198.2, 20.4, 888.0]
//5.排序sort默认升序
Arrays.sort(b);
System.out.println(Arrays.toString(b));
//6.对数组中的数据进行排序(对对象进行排序)
Stu[] ss = new Stu[4];
ss[0]=new Stu("一",100,12);
ss[1]=new Stu("二",134,123);
ss[2]=new Stu("二",134,123);
ss[3]=new Stu("四",30,19);
//用sort不能直接对对象进行排序
//方式1:让该对象的类实现Comparable接口然后重写compareTo方法
Arrays.sort(ss);
System.out.println(Arrays.toString(ss));
//方式2:Comparator比较器对象(用来制定对象的比较规则)
Arrays.sort(ss, new Comparator<Stu>() {
@Override
public int compare(Stu o1, Stu o2) {//有一个抽象方法compare来比较两个对象
//制定比较规则 :左边对象o1,右边对象o2
//约定:左边对象大于右边对象请您返回正整数
//左边对象小于右边对象请您返回负整数
//左边对象等于右边对象请您返回0
// if(o1.getHeight()> o2.getHeight()){
// return 1;
// } else if (o1.getHeight()<o2.getHeight()) {
// return -1;
// }return 0;
return Double.compare(o1.getHeight(), o2.getHeight());
}
});
System.out.println(Arrays.toString(ss));
}
学生类:
public class Stu implements Comparable<Stu>{
private String name;
private double height;
@Override
public String toString() {
return "Stu{" +
"name='" + name + '\'' +
", height=" + height +
", age=" + age +
'}';
}
public Stu() {
}
public Stu(String name, double height, int age) {
this.name = name;
this.height = height;
this.age = age;
}
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public int compareTo(Stu o) {//制定比较规则
//this与o比较
//约定:左边对象大于右边对象请您返回正整数
//左边对象小于右边对象请您返回负整数
//左边对象等于右边对象请您返回0
// if(this.age>o.age){
// return 1;
// }else if(this.age < o.age){
// return -1;
// }else{
// return 0;
// }
return this.age - o.age;//简写
//如果想降序就o.age - this.age
}
}