Java comparator Comparable and Comparator

To implement the java class definition from the comparison, the following two interfaces:

The Comparable (internal sorting) int compareTo (Object obj); return value int, default ascending sort
Comparator (external sorting) int compare (Object ob1, Object obj2); return value int, flexible ordering



java.lang.Comparable interfaces (internal comparator) java.lang
If a class implements Comparable (sort Interface) interfaces, it means that the class supports sorting
storage array or Collection class, directly through Collection.sort () or Arrays.sort the sorting

class implementing Comparable interface may be placed directly on or in the TreeMap TreeSet
public int compareTo (T obj);
return value of three cases:
1. the positive: the current object is greater than the target object
2.0
3. character input

Import java.util.Set;
 Import java.util.TreeSet; 

// comparator Person class (in ascending order of age) 
class Test2 { 


    public  static  void main (String [] args) { 
        the Set <Person> SET = new new TreeSet <> (); 
        set.add ( new new the Person ( "Joe Smith", 20 is )); 
        set.add ( new new the Person ( "John Doe", 21 is )); 
        set.add ( new new the Person ( "John Doe", 22 )) ; 
        System.out.println (SET); 
    } 


} 
class the Person the implements the Comparable <the Person> {
    private String name;
    private int age;

    public Person(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setAge(int age) {
        this.age = age;
    }

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


    public int compareTo(Person o) {
//        if (this.age > o.age ) {
//            return 1 ;
//        }else if (this.age < o.age ){
//            return -1 ;
//        }else {
//            return this.name.compareTo(o.name) ;
//        }
//    }
        return  o.getAge()-this.getAge();

    }
}

 



Comparator (1.2 java.util) external comparator
Comparator (external sort Interface): If you order a custom control class and the class itself does not support ordering (class does not implement the Comparable interface)
we can build a class "more is "to sort
comparator comparator interface to implement

" comparator: "class that implements the interface comparator as a comparator, to sort by class of the comparator
int compare (T o1, T o2 ) return value returned compareTo exactly the same value


import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;

//Person类的比较器(按照年龄升序)
class AscAgeComparator implements Comparator<Person> {
    @Override
    public int compare(Person o1,Person o2){
        return o2.getAge() - o1.getAge();
    }

    public static void main(String[] args) {
        Set<Person> set = new TreeSet<>(new AscAgeComparator());
        set.add(new Person("张三",20));
        set.add(new Person("李四",19));
        System.out.println(set);
    }
}
class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

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

 


Comparable and Comparator compared to the comparative method has been fixed, not flexible enough
to achieve the Comparator interface to third-party sort - Strategy mode, this method is more flexible and can easily change the

Comparable interface to be sorted, if a class implements the Comparable interface, which means that the class supports sorting, is an internal comparator (themselves and others than)
comparator interface is relatively interface, the class itself does not support sorting, exclusively by a number of third-party comparator (comparator class that implements the interface) to class sorting,
it is an external comparator (policy mode) determination of repeating elements TreeSet and TreeMap rely Comparable interface or comparator to distinguish between repeating elements custom class to be preserved, or in the TreeMap TreeSet: 1. Comparable interface either directly implement the class, cover write CompareTo method 2. either implement a comparator incoming TreeSet or TreeMap for external comparison and HashSet and HashMap does not depend comparison interface. At this time, in order to distinguish between whether to repeat custom elements, you need to override equals and hashCode method to determine the contents of the two elements are equal principle override equals method: 1. reflexive: for any reference value x, x.equals (x) returns true 2. symmetry: for any non-empty x, y, iff returns true x.equals (y), y.equals ( x) returns true



















3. transitive: s non-empty for any x, y, z, if x.equals (y) returns true, y.equals (z) returns true true, then x.equals (z) returns true

. 4. consistency: for any non-empty x, y, if x and y does not change the properties, multiple calls x.equals (y) always returns true or to false

5. the non-empty: for any reference x, x .equals () null return false must



first call hashCode calculated hash code decision objects stored in the tub
and then used to compare elements equals equality, if equal, no element is placed; if equals returns false, the same barrel after use the list several elements chain up

default object address object hashcode method provided by the hash


if two objects equals method returns true, they are bound to equal hashcode
Conversely, if two objects are equal hashcode, equals not necessarily equal

if and only when all equals and hashcode method returns true, just think two objects are really equal


significance hash table:
Why did you bucket to hold the elements?
In order to optimize the number of lookups exist by searching with the same hash value to find in the tub and the corresponding list of elements which require

additional: String class implements Comparable natural interface, comprising natural comparability rewritten Comparable interface int compareTo method of comparing the length of the string
that he has two compareTo method, and the other is compareToIgnoreCase
 

Guess you like

Origin www.cnblogs.com/hetaoyuan/p/11240297.html