Java comparable and comparator interface differences

Source: Internet
Author: User
Tags comparable

Comparable introduction

Comparable is the sort interface.

If a class implements the comparable interface, it means " this class supports sorting ." The class that implements the comparable interface supports sorting, assuming that there is now "a list (or array) of objects of the class implementing the comparable interface," then the list (or array) can be passed collections.sort (or Arrays.sort) to sort.

In addition, the "object of the class that implements the comparable interface" can be used as a key in an ordered map (such as treemap) or an element in an ordered collection (TreeSet), without specifying a comparer.

Comparable definition

The comparable interface only includes a function, which is defined as follows:

Package Java.lang;import java.util.*;p ublic interface comparable<t> {public    int compareTo (T o);}

Description
Suppose we "compare the size of x and Y" by X.compareto (y). If "negative" is returned, it means "x is smaller than Y"; return "0", meaning "x equals Y"; return "positive number", meaning "x is greater than Y".

Comparator Introduction

The Comparator is the comparator interface.

If we need to control the order of a class, and the class itself does not support ordering (that is, it does not implement the comparable interface), then we can create a "comparer for this class" to sort by. This "comparator" only needs to implement the comparator interface.

That is, we can create a new comparer by implementing the comparator class , and then sort the classes through the comparer.

Comparator definition

The Comparator interface consists of only two functions, which are defined as follows:

Package Java.util;public interface Comparator<t> {    int compare (t O1, T O2);    Boolean equals (Object obj);}

Description
(01) If a class is to implement the comparator interface: it must implement the CompareTo (t O1, T O2) function, but it can not implement the Equals (Object obj) function.

Why can I not implement the Equals (Object obj) function? Because of any class, the default is that you have implemented the Equals (Object obj). All classes in Java inherit from Java.lang.Object and implement the Equals (Object obj) function in Object.java, so all other classes are equivalent to implementing the function.

() int compare (t O1, T O2) is "Comparing the size of O1 and O2". Returns "negative number", meaning "O1 is smaller than O2"; returning "0" means "O1 equals O2"; returning "positive number" means "O1 is greater than O2".

Comparison of Comparator and comparable

Comparable is a sort interface, and if a class implements the comparable interface, it means "this class supports sorting."
And comparator is a comparator; if we need to control the order of a class, we can create a "comparer for that class" to sort by.

It is easy to see that comparable is equivalent to an "internal comparator", while comparator is equivalent to an "external comparator".

Example:

 Public classComparecomparatorandcomparabletest { Public Static voidmain (String [] args) {ArrayList<Person> list =NewArraylist<person>(); List.add (NewPerson ("CCCC", 20)); List.add (NewPerson ("DSSDFJ", 30)); List.add (NewPerson ("VVV", 10)); List.add (NewPerson ("SSSs", 50)); System.out.println ("Original Sort:list" +list);        Collections.sort (list); System.out.println (After the sort list by name: "+list); Collections.sort (list,Newascagecomparator ()); System.out.println ("After Asc_sort by age:" +list); Collections.sort (list,Newdscagecomparator ()); System.out.println ("After Dsc_sort by age:" +list); }}classPersonImplementsComparable<person>{    intAge ;    String name;  PublicPerson () { age= 0; Name= ""; }         PublicPerson (String name,intAge ) {         This. Age =Age ;  This. Name =name; }         Public intGetage () {returnAge ; }         PublicString GetName () {returnname; } @Override PublicString toString () {//TODO auto-generated Method Stub        returnName + ":" +Age ; } @Override Public intcompareTo (Person o) {returnName.compareto (o.name); }}classAscagecomparatorImplementsComparator<person>{@Override Public intCompare (person O1, person O2) {//TODO auto-generated Method Stub        returnO1.age-O2.age; }}classDscagecomparatorImplementsComparator<person>{@Override Public intCompare (person O1, person O2) {//TODO auto-generated Method Stub        returnO2.age-O1.age; }    }

Java comparable and comparator interface differences

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.