Numbers are sorted using a direct comparison size, and string words are sorted using the Compare () method.
Test code:
1. Sorting String objects
1 @Test2 Public voidTest17 ()throwsException {3list< String > Stringlist =NewArraylist<>();4Stringlist.add ("haha");5Stringlist.add ("123");6Stringlist.add ("Wq");7Stringlist.add ("D");8Stringlist.add ("RT");9Stringlist.add ("Uuk");TenSystem.out.println ("Before sorting:" +stringlist); OneCollections.sort (Stringlist,Newcomparator< String >() { A @Override - Public intCompare (String lhs, string rhs) { -System.out.println ("Sort string:" + LHS + "," +RHS); the - inti =Lhs.compareto (RHS); -System.out.println ("Sort result" +i); - if(I > 0 ) { + return1; -}Else { + return-1; A } at } - }); -System.out.println ("After sorting:" +stringlist); -}
Print the log:
1Before sorting: [Haha, 123, Wq, D, RT, Uuk]2Sort string: 123, haha3Sort Result-554Sort string: wq,1235 Sort Results6 sort string: Wq,haha7 Sorting Results8 sort string: D,haha9Sort Result-4TenSort string: d,123 One Sort Results A sort string: Rt,haha - Sorted Results Ten - sort string: Rt,wq theSort Result-5 - sort string: Uuk,haha - Sort Result - sort string: Uuk,wq +Sort Result-2 - sort string: Uuk,rt + Sorting Results 3 AAfter sorting: [123, D, Haha, RT, UUK, Wq]
2. Sort the numbers
1 @Test2 Public voidTest18 ()throwsException {3list< Integer > Stringlist =NewArraylist<>();4Stringlist.add (123);5Stringlist.add (32);6Stringlist.add (0);7Stringlist.add (-4);8Stringlist.add (5);9Stringlist.add (123131);TenSystem.out.println ("Before sorting:" +stringlist); OneCollections.sort (Stringlist,Newcomparator< Integer >() { A @Override - Public intCompare (integer lhs, integer RHS) { - if(LHS >RHS) { the return1; -}Else { - return-1; - } + } - }); +System.out.println ("After sorting:" +stringlist); A}
Print log:
Before sorting: [123, 0, -4, 5, 123131] after sorting: [-4, 0, 5, 32, 123, 123131]
When implementing the Compare () method of the comparator interface, return 1 represents greater than, return-1 represents less than. It is then sorted according to the return value.
Java to sort ArrayList