Common java class - a comparator

Comparable and Comparator interfaces are compared to the class 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. Can Comparable understood as internal comparator, the Comparator external comparators, substantially 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 Comparable interface class needs to implement compareTo () method, passing an external parameter for comparison, implements Comparator interface methods need to implement 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 Comparable interface can not be changed after.

 to sum up:

comparator Interface: really want to achieve only compare () method, you need a separate class to implement comparator interface, 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 's id is a positive number in ascending, descending if negative. If 0 then removed

> = 1   ascending

<= - 1 DESC

= 0 is repeated, is not recorded

comparable Interface

Such interfaces implemented without recreating a sorted class, using the interface compareble interfaces 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

Parameters: List - the list to be sorted

          C - determining the order of the list of the comparator

In Java often involves an array of objects of scheduling problems, then compare it comes to the issue 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 Object class of the equals () method;

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

Third, the definition of a single object comparator, inherited from the Comparator 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 the equals () method is often used when an object that implements its own sorted array, and to use for the java built-sort 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, the 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, from JDK1.8 emerged after Comparator interface it 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 present in the comparison operators: > , < , > = , <= , =! , == , instanceof

Only basic data types comparison, if the object can not be compared, if the comparison between the object needs to achieve in a subject, only by the Comparable , Compartor interface

( . 1 ) the 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, on behalf of the caller (this) value than o larger value

If the return value is negative, on behalf of the caller (this) value than o smaller value

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

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

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

/*

String , packaging have default implementation Comparable interface and rewritten int the 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 String 's compareTo method

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

}

}

( 2 ) Comparator Interface (custom sorting)

If a class does not implement Comparable interface, but the class he is unable to implement Comparable Interface (opening and closing principle), or a class already implements Comparable interface, but one of the compareTo does not meet our needs, then we can use Comparator interfaces manner 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/benming/p/11611965.html
Recommended