Comparator 10 are commonly used class

  

Comparable and Comparator interface class are compared to known, such as Integer, double basic data types, java can compare them, and for comparing the class, the need to manually define the field compare logic used in the comparison. Comparable can be understood as an internal comparator, and the comparator Comparator is an external, substantially the following wording:

class Apple implements Comparable<Apple>{

    int id;

    double price;

 

    public Apple(int id, double price) {

        this.id = id;

        this.price = price;

    }

    public int compareTo(Apple o) {

        //return Double.compare(this.getPrice(),o.getPrice());

        if (Math.abs(this.price-o.price)<0.001)

            return 0;

        else

            return (o.price-this.price)>0?1:-1;

    }

    @Override

    public String toString() {

        return "Apple{" +

                "id=" + id +

                ", price=" + price +

                '}';

    }

}

class AESComparator implements Comparator<Apple>{

 

    public int compare(Apple o1, Apple o2) {

        if (Math.abs(o1.price-o2.price)<0.001)

            return 0;

        else{

            return (o1.price-o2.price)>0?1:-1;

        }

    }

}

 Implements the Comparable interface class needs to implement compareTo () method, passing an external parameter for comparison, implements Comparator interface need to implement the method compare () method, passing on the outside of two classes are compared, so that the external method called when you compare.

 The difference is achieved Comparator interface code more flexible, you can define a plurality of comparators class, so the free calls based on the actual scene at the time of ordering, and can not be changed after Comparable interface.

 to sum up:

comparator Interface: really want to achieve only compare () method, you need a separate class to implement a comparator, the class will sort the class of the specified class

public int compare(Emp o1,Emp,o2){

     return o1.id - o2.id

}

It is said that if o1 of id - o2 is positive id's on ascending, descending if negative. If you reject 0

> = 1 ascending

<= - 1 DESC

Repeat = 0, no record

comparable Interface

Such interfaces implemented without recreating a sorted class, the interface using an interface compareble sort, as long as the rewriting inside the compareTo () method

Collections class is a wrapper class that includes various sets of static methods operation. Like a utility class.

Collections.sort()

sort () sorting method specified list sort ascending order according to the natural elements

public static <T> void sort (List <T> list, Comparator <>), sort the list according to the order specified by the specified comparator, all of the elements in the list must be used to specify each comparator comparing

To sort the list list-- Parameters:

          Determining the order of the list C-- comparator

In Java scheduling problems often involve an array of objects, then it comes to the comparison issues between objects.

Usually between objects can be seen in two ways:

First: the address of the object is the same, that is, whether or not reference the same object from. This way you can directly use the "==" to complete.

Second aspect: In a certain angle to compare the properties of the object.

From the latest JDK8, there are three ways to achieve the object of comparison:

A, override equals () method of class Object;

Second, inheritance Comparable interface, and implement the compareTo () method;

Third, the definition of a single object comparator Comparator inherited from the interface, compare () method.

Due to the use of different sort of way, the specific choice of which method to achieve the object of the comparison will be different.

Override equals () method is often used when an object that implements its own sorted array, while for the built-in to use java sorting algorithm using the latter two ways are possible.

First look at the second way, this way is to make their written class inherits Comparable interface and implement compareTo () method, in this case, the use java.util.Arrays.sort ()

When the method, do not specify a specific comparator, sort () method uses the object's own comparison function to complete the sequencing of the object. The following is a specific example:

[java] view plain copy

import java.util.Arrays;  

class BookCook implements Comparable<BookCook>{  

    private String title;  

    private double price;  

    public BookCook(String title,double price){  

        this.title = title;  

        this.price = price;  

    }  

    @Override  

    public String toString() {  

        return "Title:" + this.title + ", the price:" + this.price;  

    }  

    @Override  

    public int compareTo(BookCook o) {  

        if(this.price > o.price){  

            return 1;  

        }else if(this.price < o.price){  

            return -1;  

        }else{  

            return 0;  

        }  

    }  

}  

Generally, we use these two methods will be able to meet the actual development issues. But when the following occurs, we need to use Comparator interface:

To improve the object on the basis of good code has been developed on the comparison function, but also do not want to change the code before, in this case, there has been Comparator interface from after JDK1.8, is a make up for this situation.

In this case, we need to define a single comparator objects, inheritance Comparator interface, and implement compare () method. Sample code is as follows:

[java] view plain copy

class Student {  

    private String name;  

    private double score;  

    public Student(String name,double score){  

        this.name = name;  

        this.score = score;  

    }  

    public double getScore(){  

        return this.score;  

    }  

    @Override  

    public String toString() {  

        return "姓名:"+this.name+",分数:"+this.score;  

    }    

}  

class StudentComparator implements Comparator<Student> {  

    @Override  

    public int compare(Student o1,Student o2) {  

        if(o1.getScore() > o2.getScore()){  

            return 1;  

        }else if(o1.getScore() < o2.getScore()){  

            return -1;  

        }else{  

            return 0;  

        }  

    }  

}  

public class TestComparator {  

    public static void main(String[] args) {  

        Student[] sts = new Student[]{  

                new Student("小戴",60),  

                new Student ( "Wang", 90),  

                new Student ( "Pharaoh", 80),  

                new Student ( "Kogaya", 95)  

        };    

        java.util.Arrays.sort(sts, new StudentComparator());  

        System.out.println(java.util.Arrays.toString(sts));  

    }  

}  

Java, there is a comparison operator:>, <,> =, <=, =, ==, instanceof!

Only basic data types comparison, if the object can not be compared, if the comparison between the need to achieve objects in the object, only through Comparable, Compartor interface

(1) Comparable Interface (natural ordering)

String, default packaging have been achieved mt4 download tutorial Comparable interface, and rewrite the int compareTo (T o) method (defined collation), so String, and packaging can all be sorted

The default is to sort in ascending

int compareTo(T o)

If the return value is a positive number, representing the value of the caller (this) is larger than the value o

If the return value is negative, the value representing the caller (this) is smaller than the value o

If the value is 0, the value representative of the caller (this) is equal to the ratio of the value of o

If a custom class needs to implement sorting function, so that the current rules class implements Comparable interface, override int compareTo (T o) method, rewritten in the method of sorting

If a class implements Comparable interface once, the object of this class anywhere can be sorted or compare

/*

String, and packaging have been achieved Comparable interface by default, and override the int compareTo (T o) Method

*/

public class CompareDemo {

public static void main(String[] args) {

int[] arr = {5,4,2,1,3};

Arrays.sort(arr);

System.out.println(Arrays.toString(arr));

 

String[] s = {"AA","CC","ZZ","BB","JJ"};

Arrays.sort(s);

System.out.println(Arrays.toString(s));

}

}

/*

Comparison between objects

*/

public class CompareDemo {

public static void main(String[] args) {

Employee[] e = new Employee[5];

e[0] = new Employee("e001","Jack","d001");

e[1] = new Employee("e005","Tom","d010");

e[2] = new Employee("e010","Jack","d011");

e[3] = new Employee("e004","Rose","d005");

e[4] = new Employee("e009","Marry","d008");

Arrays.sort(e);

System.out.println(Arrays.toString(e));

}

}

class Employee implements Comparable<Employee>{

private String eno;

private String ename;

private String dept;

public String getEno() {

return eno;

}

public void setEno(String eno) {

this.eno = eno;

}

public String getEname() {

return ename;

}

public void setEname(String ename) {

this.ename = ename;

}

public String getDept() {

return dept;

}

public void setDept(String dept) {

this.dept = dept;

}

public Employee(String eno, String ename, String dept) {

super();

this.eno = eno;

this.ename = ename;

this.dept = dept;

}

public Employee() {

super();

}

@Override

public String toString() {

return "Employee [eno=" + eno + ", ename=" + ename + ", dept=" + dept + "]";

}

@Override

public int compareTo(Employee o) {

// With a String method compareTo

return this.eno.compareTo(o.eno);

}

}

(2) Comparator Interface (custom sorting)

If a class does not implement the Comparable interface, but the class he is unable to implement the Comparable interface (on-off principle), or a class already implements Comparable interface, but one of the compareTo does not meet our needs, then we can use Comparator interface way custom sorting

The default ascending

int compare(T o1,T o2)

o1> o2 returns a positive number

o1 <o2 returns a negative

o1 == o2 return 0

public class CompareDemo {

public static void main(String[] args) {

Employee[] e = new Employee[5];

e[0] = new Employee("e001","Jack","d001");

e[1] = new Employee("e003","Tom","d010");

e[2] = new Employee("e003","Jack","d011");

e[3] = new Employee("e004","Rose","d005");

e[4] = new Employee("e002","Marry","d008");

Arrays.sort(e, new Comparator<Employee>() {

@Override

public int compare(Employee o1, Employee o2) {

if(o1.getEno().compareTo(o2.getEno())!=0) {

return o1.getEno().compareTo(o2.getEno());

}else {

return -o1.getEname().compareTo(o2.getEname());

}

}

});

System.out.println(Arrays.toString(e));

}

}

class Employee {

private String eno;

private String ename;

private String dept;

public String getEno() {

return eno;

}

public void setEno(String eno) {

this.eno = eno;

}

public String getEname() {

return ename;

}

public void setEname(String ename) {

this.ename = ename;

}

public String getDept() {

return dept;

}

public void setDept(String dept) {

this.dept = dept;

}

public Employee(String eno, String ename, String dept) {

super();

this.eno = eno;

this.ename = ename;

this.dept = dept;

}

public Employee() {

super();

}

@Override

public String toString() {

return "Employee [eno=" + eno + ", ename=" + ename + ", dept=" + dept + "]";

}

}

Guess you like

Origin www.cnblogs.com/beimo/p/11938420.html