Implementation of Java objects Sort: comparable interfaces and interfaces camparator

1. To achieve Comparable interface (replication comparaTo Method)

Mainly to do their own comparison

2. implement a comparator

Mainly to do third-party comparison

3.

我自己做项目遇到的是 **同一类的对象** 进行比较
所以我选择的是**实现comparable接口**:

Sample Code (unsorted)
Here Insert Picture Description
Here Insert Picture Description
results
Here Insert Picture Description , we can see yet not sorted result of traversing the arraylist age is disordered

4. Now we want to achieve comparable interface to enable an orderly output

The first step
in the need to compare object's class to achieve comparable interfaces I fill up a generic
Here Insert Picture Description

The second step in this class comparaTo replication method
Here Insert Picture Description
call the sort method in the third step in the main () method
because I have a collection so I use the sort collections calls ()

Here Insert Picture Description
The results of
age also ordered the
Here Insert Picture Description

Published 15 original articles · won praise 0 · Views 4100

Guess you like

Origin blog.csdn.net/SkyingData/article/details/104093455