Collections in Java Detailed explanation of sort sorting function usage

Comparator is an interface that can override the compare () and equals () methods for price comparison; If it is null, the default order of elements is used, such as a, B, C, D, e, F, G, that is, a, G, and of course, numbers.

Compare (a, b) method: return negative integer, zero or positive integer respectively according to the first parameter less than, equal to or greater than the second parameter.

Equals (obj) method: returns true only if the specified object is also a comparator and the same sort as this comparator is enforced.

Collections. sort(list,new PriceComparator()); The second parameter of returns an int value, which is equivalent to a flag that tells the sort method in what order to sort the list.

The specific implementation code method is as follows:

Book entity class:

Custom comparator and test class:

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>