java_Comparator Interface

If a class has been developed, but in the early stages of establishing such does not implement Comparable interface, and this was not sort of operation that type. To solve this problem, Java defines another comparator interfaces comparator interface. Interface is defined as follows:

public interface Comparator<T>{
    public int compare(to1,to2);


    boolean equals(Object obj);
}

Such can be found there is also a compare method, also returns 0-11;
and before the difference is, we need to define a special class of parity rules in order to sort the array.

Let's create a new student class that contains the names and ages of the two fields, and sorting by age:


public class Student2 {
    private String name;
    private int  age;

    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;
    }


    @Override
    public String toString() {
        return "Student2{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    @Override
    public boolean equals(Object obj) {

        if(this == obj){
            return true;
        }
        if(!(obj instanceof Student2)){
            return  false;
        }

        Student2 stu = (Student2)obj;
        if(stu.name.equals(this.getName())&& stu.age == this.age){
            return true;
        }else{
            return  false;
        }



    }
}

Comparator rule class:

public class StudentComparator implements Comparator<Student2> {

    @Override
    public int compare(Student2 o1, Student2 o2) {
        if(o1.equals(o2)){
            return 0;
        }else if(o1.getAge() <o2.getAge()){
            return 1;
        }else {
            return -1;
        }
    }
}

test:

    @Test
    public void test(){
        Student2 stu[] = {new Student2("张三",24),
                new Student2("李四",22),
                new Student2("王五",19),
                new Student2("赵七",20),
                new Student2("孙八",43)};

        Arrays.sort(stu,new StudentComparator());

        for (Student2 s :stu){
            System.out.println(s);
        }
    }

result:

Student2 {name = 'Sun eight', age = 43 is}
Student2 {name = 'John Doe', age = 24}
Student2 {name = 'John Doe', age = 22 is}
Student2 {name = 'Zhao seven', age = } 20 is
STUDENT2 {name = 'Wang Wu', age = 19}

We can see that the object has been in descending order according to age up.

Published 22 original articles · won praise 9 · views 30000 +

Guess you like

Origin blog.csdn.net/qq_19408473/article/details/72921357