Comparison between Java Comparator and Comparable

Source: Internet
Author: User
Tags java comparator

Comparison between Java Comparator and Comparable

1. How to sort objects by comparison?

Java basic types such as int, float, and double can be directly compared and sorted using java. util. Arrays. sort (Object []). How can we compare and sort objects? The classes we define inherit the Object class. The equals method of the Object class is used by default to compare whether two objects are equal (the hashcode is the same)

public boolean equals(Object obj) {      return (this == obj);  }  
However, the actual requirements are generally not compared in this way. You can implement the Comparable or Comparator interface to redefine object sorting.

2. Comparable

Java. lang. Comparable: int compareTo (Object o1)

This method is used to compare the current object with the o1 object and return the int value, which respectively means:

    Positive-the current object is greater than o1zero-the current object is equal to o1negative-the current object is smaller than o1 example:
    import java.util.*;class ComparableDemo{public static void main(String[] args) {Student[] stu={new Student(18,"Mark"),new Student(22,"John"),new Student(20,"Tom"),new Student(19,"Jim")};Arrays.sort(stu);for(Student s:stu){System.out.println("the age:"+s.age+",the name:"+s.name);}}}class Student implements Comparable{public int age;public String name;Student(int age,String name){this.age=age;this.name=name;}public int compareTo(Object s){       return this.age-((Student)s).age;}}
    3. Comparator

    Java. util. Comparator: int compare (Object o1, Objecto2)

    This method is used to compare o1 with o2 objects and return the int value, respectively, which means:

      Positive-o1 is greater than o2zero-o1 is equal to o2negative-o1 is less than o2 example:

      Import java. util. *; class ComparatorDemo {public static void main (String [] args) {Student [] stu = {new Student (18, "Mark"), new Student (22, "John"), new Student (20, "Tom"), new Student (19, "Jim")};/* // You can also define Comparator in the form of a Comparator
         
          
      Comp = new Comparator
          
           
      {Public int compare (Student s1, Student s2) {return s1.age-s2.age ;}}; Arrays. sort (stu, comp); */Arrays. sort (stu, new StuComparator (); for (Student s: stu) {System. out. println ("the age:" + s. age + ", the name:" + s. name) ;}} class Student {public int age; public String name; Student (int age, String name) {this. age = age; this. name = name ;}} class StuComparator implements Comparator
           
            
      {Public int compare (Student s1, Student s2) {return s1.age-s2.age ;}}
           
          
         


       
        4. Differences between the two methods: 
        

      When a class implements the Comparable interface, it indicates that the objects of this class can be compared with each other. A set composed of these class objects can be directly sorted using the sort method.
      Comparator can be seen as an algorithm implementation that separates algorithms from data. Comparator can also be used in the following two environments:
      1. if Comparable is not implemented without considering the comparison when defining a category, you can use Comparator to sort objects without changing the object itself.
      2. Multiple sorting criteria can be used, such as ascending and descending (flexible)

      That is:

      Comparable uses java. util. Collections. sort (List) or java. util. Arrays. sort (Object []).

      Comparator uses java. util. Collections. sort (List, Comparator) or java. util. Arrays. sort (Object [], Comparator)

      --- EOF ---

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.