标签:技术 形参 code 方便 整数 结果 数据 大于 实现
像String、包装类等实现了Comparable接口,进而重写了compareTo()方法,给出了比较两个对象大小的方式(从小到大的排列)
对于自定义类来说,如果需要排序。可以让自定义类实现comparable接口,重写CompareTo(obj)方法
按照年龄从小到大进行排列
public class Test {
public static void main(String[] args) {
Student[] arr = new Student[4];
arr[0] = new Student("Tom",18,100);
arr[1] = new Student("Jack",23,60);
arr[2] = new Student("Ann",20,41);
arr[3] = new Student("Lisa",21,82);
Arrays.sort(arr);
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
}
class Student implements Comparable {
private String name;
private int age;
private double grade;
public Student() {
}
public Student(String name, int age, double grade) {
this.name = name;
this.age = age;
this.grade = grade;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getGrade() {
return grade;
}
public void setGrade(double grade) {
this.grade = grade;
}
@Override
public String toString() {
return "Student{" +
"name=‘" + name + ‘\‘‘ +
", age=" + age +
", grade=" + grade +
‘}‘;
}
@Override
public int compareTo(Object o) {
//数据进行类型转换
if(o instanceof Student){
Student s = (Student)o;
//进行比较
if(s.getAge() > this.getAge()){
return -1;
}else if(s.getAge() < this.getAge()){
return 1;
}else{
return 0;
}
}else{
throw new RuntimeException("传入数据类型不一致");
}
}
}
重写compare(Object o1,Object o2)方法,比较o1和o2的大小
public void test1(){
String[] s = new String[]{"AA","YY","NN","EE","XX"};
Arrays.sort(s, new Comparator() {
@Override
public int compare(Object o1 , Object o2) {
if(o1 instanceof String || o2 instanceof String){
String s1 = (String)o1;
String s2 = (String)o2;
if(s1.equals(s2)){
return 0;
}else{
return - s1.compareTo(s2);
}
}
else{
throw new RuntimeException("传入数据类型不一致");
}
}
});
System.out.println(Arrays.toString(s));
}
标签:技术 形参 code 方便 整数 结果 数据 大于 实现
原文地址:https://www.cnblogs.com/CrabDumplings/p/13339146.html