Analysis of comparable and comparator in Java collection

Source: Internet
Author: User
Tags comparable

I. Introduction to comparable and comparator

TreeSet are generally used when comparing collection elements. For simple data types, TreeSet can be compared directly. But for complex data types, such as the data types or classes that you define, you need to set the comparison and comparison rules yourself, and you need to use comparable and comparator. Both comparable and comparator are used to implement sorting in the collection, except that comparable is the sort of method implementation that is defined within the collection, and comparator is the sort implemented outside the collection. Therefore, if you want to combine sorting, you need to define a method for the comparator interface outside the collection or to implement the comparable interface within the collection.

A class that implements the comparable interface indicates that objects of this class can be compared to each other, and that the combination of such objects can be sorted directly using the Sort method.

Comparator is a strategy mode, that is, without changing the object itself, and using a policy object to change its behavior, separating the algorithm from the data, comparator can also be used in the following two environments:

1. When the class is not designed with a comparison problem in mind and does not implement the comparable interface, it is possible to sort by comparator without modifying the original class code.

2. Class design implements the comparable interface, but later users want to compare classes with a new comparison rule

two. Usage Examples:

Comparable sort by:

First define the item class that implements the comparable interface

Package com.collection; Import java.util.Objects; /** * @author Zhu Wei * Defines the item class that implements the comparable interface * */public class item implements comparable<item>{private String DESCRI    ption;       private int partnumber;       Public Item (String adescription, int apartnumber) {description = Adescription;    PartNumber = Apartnumber;    } public String GetDescription () {return description;    The public String toString () {return "[description=" +description+ ", partnumber=" +partnumber+ "]";       } public boolean equals (Object otherobject) {if (this = = Otherobject) return true;       if (Otherobject = = null) return false;       if (GetClass ()!=otherobject.getclass ()) return false;       Item other = (item) Otherobject;    Return objects.equals (description, other.description) &&partnumber = = Other.partnumber;    } public int hashcode () {return objects.hash (description,partnumber); }//Heavy CompaReto method, sets the comparison method for the Item object @Override public int compareTo (Item other) {return Integer.compare (PartNumber,          Other.partnumber);  }    }


Defines the class in which item is sorted, sorting the collection using TreeSet or TreeMap, where the collection elements are stored with TreeSet.

Package com.collection; Import Java.util.TreeSet; public class listsortwithcomparable{public     static void Main (string[] args)    {       treeset<item> set = new Treeset<> ();       Set.add (New Item ("Zhuwei", +));       Set.add (New Item ("Yinyuchun"));       Set.add (New Item ("Xiaobai"));       Set.add (New Item ("Chun"));             for (Item It:set)       {           System.out.println (it.tostring ());       }     


Comparator Sort Implementation Example:

First define the classes that need to be sorted people

Package com.collection; public class people{    private String name;    Public String getName ()    {       return name;    }    public void SetName (String name)    {       this.name = name;    }    public int getage ()    {       return age;    }    public void Setage (int.)    {       this.age = age;    }    private int age;     Public people (String Name,int age)    {       this.name = name;       This.age = age;    }    Public String toString ()    {       return ("Name:" +this.name+ ", Age:" +this.age);}    }


Then we set up a class to sort the people, there are two ways to sort by using comparator, the first is to place the people object that needs to be sorted in the list collection, and then call Collection.sort (List,comparator) Method is ordered, the second method is to pass the comparator object directly to the TreeSet constructor, and overload the comparator class Compara method, specify the collation, this method does not need to let people class implement comparator interface, And its code is more concise.

Comparator

Package com.collection; Import Java.util.arraylist;import java.util.collection;import java.util.collections;import java.util.Comparator; Import Java.util.hashset;import java.util.list;import java.util.sortedset;import java.util.TreeSet; public class listsortwithcomparator{publicstatic void Main (string[] args) {/* * Use comparator to sort the first Method, * Define a class that implements the comparator interface, and overload the Compara method, set the comparison rule * use Collection.sort (List,comparator) method to achieve sorting, * Collect The first parameter of the Ion.sort (List,comparator) method is a list type, so the element to be sorted needs to be placed in the list set/* List<people>list = new Arraylist<&gt       ;();       List.add (Newpeople ("Zhuwei", 26));       List.add (Newpeople ("Yinyuchun", 25));        List.add (Newpeople ("Xiaobai", 26));             Mcomparatorcomparator = new Mcomparator ();             Collections.sort (List,comparator);       for (peoplep:list) {System.out.println (p.tostring ()); }/* * The second method of sorting using comparator, * This method does not require people implementation compArator interface * Direct Comparator object to TreeSet constructor, * and overload Compara method of Comparator class, specify collation *///sortedset<peop Le>set = new Treeset<> (//Newcomparator<people> ()//{//////reload Comparat Compara method of the or class, setting comparison rules: Descending by name//@Override//Publicint Compare (People people1, people people2) {////todo auto-generated method stub//if (People1.getname (). Compare                   to (People2.getname ()) >0)//{//return-1;//}//                else//{//return1;//}////     }////}//);//Set.addall (list);//System.out.println ("Output results in descending order:");//  for (Peoplep:set)//{//System.out.println (p.tostring ());/}}}


Analysis of comparable and comparator in Java collection

Related Article

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.