Arrays
int[] arr = {10,20,30,40,50,60};
system.out.println(Arrays.tostring(arr));
int[] arr2 = Arrays.copyOfRange(arr,from:1,to:4);
system.out.println(Arrays.toString(arr2));
int[] arr3 = Arrays.copyOf(arr,newLength:10);
system.out.println(Arrays.toString(arr3));[10,20,30,40,50,60,0,0,0,0]
int[] arr4 = Arrays.copyOf(arr,newLength:3);
system.out.println(Arrays.toString(arr4));[10,20,30]
double[] prices = {99.8,128,100};
Arrays.setAll(prices,new IntToDoubleFunction() {
@Override
public double applyAsDouble(int value) {
return prices[value] * 0.8;
}
});
system.out.println (Arrays.toString(prices));
Arrays.sort(prices);
System.out.println(Arrays.toString(prices));
以上都是直接用数据进行排序,那么对象怎么进行排序呢
方式一
首先先创建一个学生类
public class Student implements Comparable<Student> {
private String name;
private double height;
private int age;
@Override
public int compareTo(Student o) {
return this.age - o.age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", height=" + height +
", age=" + age +
'}';
}
public Student() {
}
public Student(String name, double height, int age) {
this.name = name;
this.height = height;
this.age = 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;
}
}
在测试类中进行测试
Student[] students =new Student[4];
students[0] = new Student("111",167,24);
students[1] = new Student("222",168,23);
students[2] = new Student("333",175,25);
students[3] = new Student("444",185,26);
Arrays.sort(students);
System.out.println(Arrays.toString(students));
方式二:
此时如果比较身高的话,不能直接用上面的减 ,因为身高是浮点型,返回值类型是int,如果两个人身高相差0.1的话就会出现相等的情况,所以要用浮点型。。。其他的代码和上面是一样的
主要是用了匿名类的构造器