Java implements Comparable and Comparator object comparison

  • 2020-05-05 11:18:47
  • OfStack

When the collection or array to be sorted is not purely numeric, Comparator or Comparable can often be used for simple object sorting or custom sorting.

A comparison function, which imposes a total ordering on some collection of objects. Comparators can be passed to a sort method (such as Collections.sort or Arrays.sort) to allow precise control over the sort order. Comparators can also be used to control the order of certain data structures (such as sorted sets or sorted maps), or to provide an ordering for collections of objects that don't have a natural ordering. ------API

The string List can be sorted directly by sort, and that's because String has implemented the Comparable interface for us, so our Person also implements a comparator if it wants to sort.

i. Comparator

Sort the objects stored in Linkedlist and


import java.util.Comparator;
import java.util.LinkedList;
class Person{
  private float height;
  private String name;
  
  Person(float height)
  {
    this.height=height;
  }
  public float getHeight() {
    return height;
  }
  public void setHeight(float height) {
    this.height = height;
  }
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
}
class PersonHeight implements Comparator<Person>{
   
  @Override
  // rewrite compare Method, return<0 The same, return>0 Then swap the order (keep the ascending order) 
  public int compare(Person e1, Person e2) {
    if(e1.getHeight() < e2.getHeight()){
      return 1;
    } else {
      return -1;
    }
  }
}
public class Question3 {
  public static void main(String[] args) {
    Person p1=new Person(23.4f);
    p1.setName("Stud1");
    Person p2=new Person(2.34f);
    p2.setName("Stud2");
    Person p3=new Person(34.32f);
    p3.setName("Stud3");
    Person p4=new Person(56.45f);
    p4.setName("Stud4");
    Person p5=new Person(21.4f);
    p5.setName("Stud5");
    
    LinkedList<Person> al=new LinkedList<Person>();
    al.add(p1);
    al.add(p2);
    al.add(p3);
    al.add(p4);
    al.add(p5);
    
        // call sort Method to implement sorting 
    Collections.sort(al, new PersonHeight());
    
        // Traverse the output 
    for(Person p:al)
      System.out.println(p.getName());
  }
}


Additional:


// Sort the dates 
/**
 *  if o1 Less than o2, Return a negative number ; if o1 Is greater than o2 Returns a positive number ; If they are equal, return 0;
 */
@Override
public int compare(Step o1, Step o2) {
  Date acceptTime1=UtilTool.strToDate(o1.getAcceptTime(), null);
  Date acceptTime2=UtilTool.strToDate(o2.getAcceptTime(), null);
  
  // The date field in ascending order, if you want to use descending order before methods 
  if(acceptTime1.after(acceptTime2)) return 1;
  return -1;
}

ii. Comparable


import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
class Person implements Comparable{
  private float height;
  private String name;
  
  Person(float height)
  {
    this.height=height;
  }
  public float getHeight() {
    return height;
  }
  public void setHeight(float height) {
    this.height = height;
  }
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  @Override
  public int compareTo(Object o) {
    // TODO Auto-generated method stub
    if(this.height>((Person)o).height){
      return 1;
    }else
    return -1;
  }
  
}
public class Question3 {
  public static void main(String[] args) {
    Person p1=new Person(23.4f);
    p1.setName("Stud1");
    Person p2=new Person(2.34f);
    p2.setName("Stud2");
    Person p3=new Person(34.32f);
    p3.setName("Stud3");
    Person p4=new Person(56.45f);
    p4.setName("Stud4");
    Person p5=new Person(21.4f);
    p5.setName("Stud5");
    
    LinkedList<Person> al=new LinkedList<Person>();
    al.add(p1);
    al.add(p2);
    al.add(p3);
    al.add(p4);
    al.add(p5);
    
    Collections.sort(al);
    
    for(Person p:al)
      System.out.println(p.getName());
  }
}

iii. Compare

Comparable is defined inside Person class .
Comparator is defined outside of Person, so there is no need to change the structure of our Person class.
Two methods have their own advantages and disadvantages of using Comparable simple, as long as the object implementing the Comparable interface becomes a comparable object directly, but need to modify the source code, with the benefits of Comparator is not to need to modify the source code, but also achieve a comparator, when a custom object need to compare, passed on the comparator with object can than size, And in Comparator, users can implement complex and generic logic by themselves, so that it can match some relatively simple objects, which can save a lot of repetitive work.


Related articles: