Comparable interface of

This section discusses two questions:

  • Sorting an array of strings
  • Ordering custom class

1. implements sorting an array of strings

public class TestSort1 {

    public static void main(String[] args) {
        String[] strs=new String[] {"zhangsan","lisi","wangwu","zhaosi"};
        Arrays.sort(strs);
        System.out.print(Arrays.toString(strs));
    }
}
Output: sorted in order of the first letter of the dictionary. 
[lisi, wangwu, zhangsan, zhaosi

2. To achieve the sort of custom classes

Create a custom class:

public class Employee1{
    private String name;
    private double salary;
    
    public Employee1(String name,Double salary) {
        this.name=name;
        this.salary=salary;
    }
    
    public String getName() {
        return name;
    }
    
    public double getSalary() {
        return salary;
    }
    
    public void raiseSalary(double byPercent){
        double raise=salary*byPercent/100;
        salary+=raise;
    }
    @Override
    public String toString() {
        return "Employee1 [name=" + name + ", salary=" + salary + "]";
    }
}

test:

public class TestSort {

    public static void main(String[] args) {
        Employee1[] e1=new Employee1[3];
        e1[0]=new Employee1("zhangsan",5000.0);
        e1[1]=new Employee1("lisi",6000.0);
        e1[2]=new Employee1("wangwu",7500.0);
        Arrays.sort(e1);
        System.out.print(Arrays.toString(e1));

    }
}

 Such written code, the compiler not being given, but a run:

java.lang.ClassCastException

Improved operation:

  Go to custom class implements Comparable interfaces and interface method definitions

public class Employee1 implements Comparable<Employee1>{ //为泛型Comparable提供参数
    private String name;
    private double salary;
    
    public Employee1(String name,Double salary) {
        this.name=name;
        this.salary=salary;
    }
    
    public String getName() {
        return name;
    }
    
    public double getSalary() {
        return salary;
    }
    
    public void raiseSalary(double byPercent){
        double raise=salary*byPercent/100;
        salary+=raise;
    }

    @Override
    public String toString() {
        return "Employee1 [name=" + name + ", salary=" + salary + "]";
    }

    @Override
    public int compareTo(Employee1 o) {
        return Double.compare(o.salary,salary);
    }
}

 result:

[Employee1 [name = wangwu, salary = 7500.0], Employee1 [name = lisi, salary = 6000.0], Employee1 [name = zhangsan, salary = 5000.0]] are arranged according to descending salary.

Conclusion: To use Arrays.sort (), defined class implements Comparable interface to go, in fact, the String class also implements Comparable interface.

Guess you like

Origin www.cnblogs.com/liu-chen/p/11873893.html