The differences and relationships between the "Java Foundation" interface comparable and comparator

Source: Internet
Author: User
Tags comparable

interface comparable and comparator differences and relationships

1). Both are the implementation of the collection of elements in the comparison, sorting;

2). Comparable is a collection of internally defined method implementation ordering, comparator is a collection of external implementation ordering

3). Comparator interface under Java.util, comparable interface under Java.lang;

Usually custom classes are added such as lists and other containers to be able to sort, can implement the comparable interface, in the Collections.sort (list<t> List, comparator<? super t> C) when sorting, If comparator is not specified, it is sorted in natural order (sorted by comparable). Comments such as API:

Sorts the specified list according to the order induced by the specified comparator. All elements in the list must is mutually comparable using the specified comparator

Sorts the specified list into ascending order, according to the <i>natural ordering</i> of its elements

While comparator is a dedicated comparator, you can write a comparator to compare the size of two objects when the object does not support self-comparison or the self-comparison function does not meet your requirements.

For example, if you want to sort integers by absolute size, the integer is not required, you don't need to modify the integer class (you can't actually do that) to change its sort behavior, just use an object that implements the Comparator interface to control its ordering.

Common classes such as String, Integer can do the comparison of the size of the operation, the reason is the implementation of the comparable interface

 Packagecom.pachira.b;ImportJava.io.FileInputStream;Importjava.util.ArrayList;Importjava.util.Collections;ImportJava.util.Comparator;Importjava.util.List;ImportJava.util.Scanner; Public classSortcount {Private StaticString TEXT = "Data/words.count"; Private StaticString charset = "GBK";  Public Static voidMain (string[] args) {if(Args.length < 2) {System.err.println ("Usage:sortcount Words.count Charset[gbk/utf8]"); System.exit (-1); } TEXT= Args[0]; CharSet= Args[1]; Sortcount D=NewSortcount ();    D.sort (); }    Private voidsort () {Try{Scanner in=NewScanner (NewFileInputStream (TEXT), CharSet); List<Word> words =NewArraylist<word>();  while(In.hasnext ()) {String sent=In.nextline (); String[] List= Sent.split ("\ t"); if(List.length >= 2){                    Try{Words.add (NewSortcount.word (List[0], Integer.parseint (list[1]))); } Catch(Exception e) {Continue;            }}} in.close (); Collections.sort (words,NewComparator<word>() {@Override Public intCompare (Word O1, Word o2) {intFirst =O2.count.compareTo (O1.count); if(First = = 0){                        returnO2.name.compareTo (o1.name); }                    returnFirst ;            }            });  for(Word word:words) {System.out.println (word); }        } Catch(Exception e) {System.err.println (E.getmessage ()); }    }    classWord {PrivateString name; PrivateInteger Count;  PublicWord (String name, Integer count) { This. Name =name;  This. Count =count; }         PublicString toString () {StringBuffer sb=NewStringBuffer (); Sb.append ( This. name + "\ T" + This. Count); returnsb.tostring (); }    }}

The differences and relationships between the "Java Foundation" interface comparable and comparator

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.