The difference between comparable and comparator __ "Java Collection"

Source: Internet
Author: User

After using collections to collect objects, if the relative objects are sorted, we can use the sort () method in Java.util.Collections, because an index is required to sort, so the collections sort () method is subject to the list action object. Use the sort () method to sort objects only according to the sort method it provides, and if you want to define collations yourself, you can manipulate the CompareTo () method in Java.util.Comparable. or the Compara () method in the Java.util.Comparator interface.

difference: The CompareTo () method of the comparable must override the method within the object of the comparison, such as the string class itself has an operation comparable, and the following sort

	List words = arrays.aslist ("B", "X", "A");
	Collections.sort (words);

It will get the result: A B X

If you need to sort reverse order at this point, you need to override the CompareTo () method inside the string class, so using CompareTo () is inconvenient in some cases

The Compara () method in the comparator interface does not have this requirement, it can override the Compara () method in another class, and finally call the class

	list<map.entry<string, integer>> list = new arraylist<> (Map.entryset ());
	Collections.sort (list, new Valuesort ());
	for (int i = 0; i < list.size (); i++)
		System.out.print (List.get (i) getkey ());

Class Valuesort implements Comparator<map.entry<string, integer>> {

	@Override public
	int Compare ( Entry<string, integer> O1, entry<string, integer> O2) {
		if ((O1.getvalue ()-O2.getvalue ()) > 0)
			R eturn-1;
		else if (O1.getvalue ()-o2.getvalue () = 0)
				&& (O1.getkey (). CharAt (0)-O2.getkey (). CharAt (0) > 0) 
  return-1;
		return 1;
	}
}

Rewrite the Compare () method in class Valuesort, and then use Collections.sort (list, new Valuesort ()) to call the class and sort the list

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.