Requirement scenario description:You need to sort a Collection in some way. For example, we need to sort a collection of User objects by company and name. The User object is as follows: The code is as follows:Copy code Package com. guoweiwei.
Differences between Comparable and Comparator
Both Comparable and Comparator are used to compare and sort elements in a set,Comparable is inside the setSorting of defined methods,Comparator is outside the setSo, to achieve sorting, You need to
Comparable and Comparator in java
Comparable and Comparator in java
-Comparable Interface
Interface Definition
public interface Comparable
{ public int compareTo(T o); }
This interface only contains a compareTO () function,
Sometimes you need to sort the elements in the logarithm group. Of course, you can write a proper sorting method by yourself, but since the Java package contains the arrays. Sort sorting methodWhy not use an array with few elements?
Sorting an array
First, describeCustom classes are sorted in a certain way, such as when a person class is ordered from small to large according to age, such as a student class to be ranked from highest to lowest by grade.Here we take two ways, one is to use the
comparable and comparator in Java
-comparable interfaceInterface definitionpublicinterface ComparableT> { publicint compareTo(T o); } The interface contains only one CompareTo () function,int CompareTo (object o): Compares the current
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
The Java comparator has two classes, namely the comparable interface and the comparator interface.
When sorting an array of objects , the comparator works very clearly, first of all, to explain the comparable interface.
Let the object that needs to
In our usual use of collection, it is very often necessary to sort the elements inside. For this sort, there are usually two ways to implement this:1. Create a comparator class to implement the comparator interface, and then apply the sort method
Comparable vs. Comparator
Comparable and Comparator are two interfaces provided by Java core APIs. From their names, we can roughly guess that they are used to compare some things in some way. But what are the differences between them? The following
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.