先创建一个学生类
package Arrays类;
public class Student {
private String name;
private int age;
private double height;
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the age
*/
public int getAge() {
return age;
}
/**
* @param age the age to set
*/
public void setAge(int age) {
this.age = age;
}
/**
* @return the height
*/
public double getHeight() {
return height;
}
/**
* @param height the height to set
*/
public void setHeight(double height) {
this.height = height;
}
public Student(String name, int age, double height) {
super();
this.name = name;
this.age = age;
this.height = height;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + ", height=" + height + "]";
}
public Student() {
super();
}
}
记得对toString方法在学生类中重写,一会我们会直接输出,你不重写打的就是地址
创建一个测试类
要注意对浮点类型的数据排序,如对身高的排序,想要用一行代码直接写完,就需要用到
Double.compare系统帮我们写好了
public class Test2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Student[] arr=new Student[3];//创建一个学生类型的数组
arr[0]=new Student("张三",18,177.3);
arr[1]=new Student("李四",14,160.2);
arr[2]=new Student("小明",26,163.2);
System.out.println(Arrays.toString(arr));
//输出没有排序的内容[Student [name=张三, age=18, height=177.3], Student [name=李四, age=14, height=160.2], Student [name=小明, age=26, height=163.2]]
Arrays.sort(arr, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
// TODO Auto-generated method stub
return o1.getAge()-o2.getAge(); //按年龄升序
//return Double.compare(o2.getHeight(), o1.getHeight());//按照身高降序排
}
});
System.out.println(Arrays.toString(arr));
}
}
这里是Double.compare的源码,和对整数排序的规则是一样的
arrays.sort(参数1,参数2)
参数1为被排序的数组,必须是引用类型的数组
参数2:匿名内部类,代表了一个比较器对象
在普通的Integer排序中可以写
if(o1>o2) {
// return 1;
// }
// else if (o1<o2) { //升序相仿即降序
// return -1;
//
// }
// return 0;
或者写一行语句
return o1-02升序
return 02-01降序
public static int compare(double d1, double d2) {
if (d1 < d2)
return -1; // Neither val is NaN, thisVal is smaller
if (d1 > d2)
return 1; // Neither val is NaN, thisVal is larger
// Cannot use doubleToRawLongBits because of possibility of NaNs.
long thisBits = Double.doubleToLongBits(d1);
long anotherBits = Double.doubleToLongBits(d2);
return (thisBits == anotherBits ? 0 : // Values are equal
(thisBits < anotherBits ? -1 : // (-0.0, 0.0) or (!NaN, NaN)
1)); // (0.0, -0.0) or (NaN, !NaN)
}