Sometimes you need to sort the list by using the sort () method of the collections, instead of sorting it yourself.
PackagemyTest;Importjava.util.ArrayList;Importjava.util.Collections;ImportJava.util.Comparator;Importjava.util.List; Public classMyTest {StaticList<integer> myList =NewArraylist<integer>(); Public Static voidMain (String args[]) {Init (); Sort (); Show (); } Public Static voidInit () {Mylist.add (123); Mylist.add (45); Mylist.add (5); Mylist.add (123); Mylist.add (97); Mylist.add (583); Mylist.add (286); Mylist.add (534); Mylist.add (1000); Mylist.add (998); } Public Static voidSort () {Collections.sort (myList,NewComparator<integer>() { Public intCompare (integer O1, integer o2) {//TODO auto-generated Method Stub if(O1 <O2) { return-1; } Else if(O1 = =O2) { return0; } Else { return1; } } }); } Public Static voidShow () { for(inti=0; I<mylist.size (); i++) {System.out.println (string.valueof (i)+ ":" +Mylist.get (i)); } }}
The results of the operation are as follows:
This is the sort from small to large, if the "<" is changed to ">", it is from the big to the small sort.
List sort in Java