Java implements sorting of List objects in a certain way
Requirement: sort and output the data in a set in a certain way. For example, if the object stored in the set is Person, the List set is used to store the data from large to small, if you want to compare objects in java, You can implement the Comparable interface. Now let's take a look at how the Comparable interface documentation describes
Interface Comparable
Type parameter:
T
-For the types of objects that can be compared with this object, the Comparable interface must implement CompareTo (T o) to compare the order of this object with the specified object. If the object is smaller than, equal to, or greater than the specified object, a negative integer, zero, or positive integer is returned. Now code test Person. java
Public class Person implements Comparable
{Private int age; private String name; public int getAge () {return age;} public void setAge (int age) {this. age = age;} public String getName () {return name;} public void setName (String name) {this. name = name;} public Person (int age, String name) {super (); this. age = age; this. name = name ;}@ Overridepublic int compareTo (Person o) {if (this. age> o. age) {return 1;} else if (this. age
PersonTest. java
Public class PersonTest {public static void main (String [] args) {Person p1 = new Person (24, "zhangsan"); Person p2 = new Person (25, "zhangsan1"); Person p3 = new Person (23, "zhangsan2"); Person p4 = new Person (22, "zhangsan3"); List
Persons = new ArrayList
(); Persons. add (p2); persons. add (p1); persons. add (p4); persons. add (p3); for (int I = 0; I
Print result:
Zhangsan1 :::::: 25
Zhangsan :::::: 24
Zhangsan3 ::::: 22
Zhangsan2 ::::: 23
The printed results show that the data in the set is not sorted by age, because the List set is not sorted by age. If you want to output data by age, you must sort the set by age. Collections. sort (list );
If you use a TreeSet set, you can sort objects.