1 Packageobject comparison sort;2 3 Importjava.util.Arrays;4 5 classAImplementsComparable<a>{6 PrivateString name;7 Private intAge ;8 PublicA (String name,intAge ) {9 This. name=name;Ten This. age=Age ; One } A @Override - Public intCompareTo (A o) {//This method does not need to be called manually, and arrays automatically calls the - if( This.age<o.age) the return-1;//1.this is less than the return negative, this is greater than the return positive, ascending; - if( This.age>o.age) - return1;//2.this is less than the return positive, this is greater than the return negative, then descending; - return0;//equal return 0 + } - @Override + PublicString toString () { A return"Name=" +name+ ", age=" +age+ "\ n"; at } - } - Public classtestcomparable { - Public Static voidMain (string[] args) { -A[] As=Newa[]{ - NewA ("Zhang San", 63), in NewA ("John Doe", 33), - NewA ("Harry", 53), to NewA ("Zhao Liu", 43), + }; - Arrays.sort (AS); the System.out.println (Arrays.tostring (AS)); * } $}View Code
Operation Result:
[Name= John Doe, age=33
, Name= Zhao Liu, age=43
, Name= Harry, age=53
, Name= Zhang San, age=63
]
The "Java" Implementation of the interface comparable<t> interface int compareTo (T O) method implements the ordering of an array of objects or a linked list or collection