Comparable and Comparator

<strong>To implement comparison of custom classes in java, the following two interfaces are provided:<br></strong>

Comparable (internal sorting) int compareTo(Object obj); the return value is int, the default is ascending order Comparator (external sorting) int compare(Object ob1,Object obj2); the return value is int, Flexible sorting

<br><br> <strong>java.lang.Comparable interface (internal comparator)java.lang</strong><br><strong>If a class implements the Comparable (sorting interface) interface, it means that the class supports sorting</strong><br><strong> The Collection or array that stores this class can be sorted directly through Collection.sort() or Arrays.sort</strong><br><br><strong> Classes that implement the Comparable interface can be stored directly in TreeSet or TreeMap</strong><br><strong> public int compareTo(T obj);</strong><br><strong>Three cases of return value:</strong><br><strong> 1. Positive number: the current object is larger than the target object</strong><br><strong>2.0</strong><br><strong> 3. Fushu</strong><br><br>
import java.util.Set;
import java.util.TreeSet;

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


    public static void main(String[] args) {
        Set<Person> set = new TreeSet<>();
        set.add(new Person("Zhang San",20));
        set.add(new Person("李思",21));
        set.add(new Person("李思",22));
        System.out.println(set);
    }


}
class Person implements Comparable<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();

    }
}
<br><strong> Comparator(1.2 java.util) external comparator</strong><br><strong> Comparator (external sorting interface): If you use to control the order of a custom class and the class itself does not support sorting (the class does not implement the Comparable interface)</strong><br><strong>We can create a "comparator" of this type for sorting</strong><br><strong> The comparator can implement the Comparator interface</strong><br><br><strong> "Comparator:"A class that implements the Comparator interface is used as a comparator, and classes are sorted through this comparator</strong><br><strong> The return value of int compare(T o1,T o2) is exactly the same as the return value of compareTo</strong><br><br><br>
import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;

//Comparator of Person class (in ascending order by age)
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("Zhang San",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 +
                '}';
    }
}
<br><strong> Compared with Comparator, the comparison method is fixed and not flexible enough</strong><br><strong> Implemented the Comparator interface for third-party sorting - strategy mode. This method is more flexible and can be easily changed</strong><br><br><strong>Comparable is a sorting interface. If a class implements the Comparable interface, it means that the class supports sorting and is an internal comparator (compare yourself with others)</strong><br><strong> The Comparator interface is a comparator interface. The class itself does not support sorting. Several third-party comparators (classes that implement the Comparator interface) are used to sort the classes.</strong><br><strong>Is an external comparator (strategy mode)</strong><br><br><strong>Judgment of repeated elements</strong><br><strong>TreeSet and TreeMap rely on the Comparator or Comparable interface to distinguish repeated elements</strong><br><br><strong> To save a custom class in a TreeSet or TreeMap:<br></strong><br> <strong>1. Either the class directly implements the Comparable interface and overrides the CompareTo method<br></strong><br><strong> 2. Either implement a comparator and pass it in to TreeSet or TreeMap for external comparison</strong><br><br><strong>HashSet and HashMap do not rely on comparison interfaces. At this time, in order to distinguish whether the custom element is repeated, you need to override the equals and hashCode methods at the same time to determine the content of the two elements</strong><br><strong>Equal</strong><br><br> <strong>Principles for overriding the equals method:</strong><br><strong> 1. Reflexivity: For any non-null reference value x, x.equals(x) returns true</strong><br><br><strong> 2. Symmetry: For any non-empty x, y, if and only if x.equals(y) returns true, y.equals(x)</strong><br><strong>Also returns true</strong><br><br><strong> 3. Transitivity: For any non-empty x, y, z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) also returns true</strong><br><br><strong> 4. Consistency: For any non-empty x, y, if the attributes in x and y have not changed, calling x.equals(y) multiple times will always return true or false</strong><br><br><strong> 5. Non-nullability: For any non-null reference x, x.equals()null must return false</strong><br><br><br><br><strong> First call hashCode to calculate the hash code of the object and determine the bucket to store it</strong><br><strong> Then use equals to compare whether the elements are equal. If they are equal, no more elements will be placed; if equals returns false, use a linked list to link several elements after the same bucket</strong><br><br><strong>The hashcode method provided by Object uses the address of the object for hashing by default</strong><br><br><br><strong> If the equals method of two objects returns true, their hashcodes must be equal</strong><br><strong> Conversely, if the hashcodes of two objects are equal, equals is not necessarily equal</strong><br><br><strong> If and only if the equals and hashcode methods both return true, the two objects are considered truly equal</strong><br><br><br><strong>The meaning of hash table:</strong><br><strong> Why buckets to store elements? </strong><br><strong> In order to optimize the number of searches, it exists to find the required elements in the corresponding buckets and linked lists by searching for the same hash value.<br><br>In addition: the String class naturally implements the Comparable interface, so it is naturally comparable. It rewrites the int compareTo method in the Comparable interface to compare the string length.<br>He has two compareTo methods, the other is compareToIgnoreCase<br></strong>
<strong>The relationship between Set interface and Map interface</strong><br><strong>Set is actually a Map internally. The saved single element is stored in the key of the map and cannot be repeated</strong><br><strong>The hashSet determines whether two objects are duplicates. The basis for determination is equals (to determine whether the addresses of two objects are equal) and hashCode</strong><br><br><strong>To save an element in a TreeSet, either the class of the element itself must implement Comparable, or Comparator must be passed in externally</strong><br><br><strong>The key in the map cannot be repeated, but the value can be repeated, and the default is empty</strong><br><strong>hashCode gets the hash code of any object</strong><br><strong>equals compares whether two objects are equal</strong>
<strong> </strong>