Java provides us with a set of tool classes that allow us to manipulate collections, and the methods are static.
Collections.sort () method, parameter:list<t> Collection Object, this object with generics, is to ensure that the elements in the collection are comparable, so that the return value of the generic will be a special point, <t extends comparable <? Super T>>
The default sort string, in alphabetical order
If it is in Chinese, the default is to sort by ASCII encoding
Customize a comparer to sort by the length of the string
Defining a class Strcomparator implementing the Comparator class
Implementation Method Compare (), Parameters:
Importjava.util.ArrayList;Importjava.util.Collections;ImportJava.util.Comparator;Importjava.util.List; Public classCollectionsdemo {/** * @paramargs*/ Public Static voidMain (string[] args) {List<String> list=NewArraylist<string>(); List.add ("AAA"); List.add ("CCC"); List.add ("BBB"); List.add ("Eee"); SYSTEM.OUT.PRINTLN (list);//output [AAA, CCC, BBB, Eee]Collections.sort (list); SYSTEM.OUT.PRINTLN (list);//output [AAA, BBB, CCC, EEE]List<String> list2=NewArraylist<string>(); List2.add (Dow); List2.add (Tips); List2.add (Culvert); System.out.println (LIST2);//output [Tao, Shi, Han]Collections.sort (LIST2); System.out.println (LIST2);//output [Shi, Han, Tao]List<String> list3=NewArraylist<string>(); List3.add ("AAA"); List3.add (C); List3.add ("BB"); List3.add ("Eeee"); System.out.println (LIST3);//output [AAA, C, BB, Eeee]Collections.sort (List3,Newstrcomparator ()); System.out.println (LIST3);//output [C, BB, AAA, Eeee] }}/*** Custom Comparator *@authorTaoshihan **/classStrcomparatorImplementsComparator<string>{@Override Public intCompare (String O1, String O2) {if(O1.length () >o2.length ()) { return1; }Else if(O1.length () <o2.length ()) { return-1; } returnO1.compareto (O2); } }
PHP Version:
<?PHP$list=Array("AAA", "CCC", "BBB", "Eee"));Sort($list);Print_r($list);//output Array ([0] = AAA [1] = BBB [2] = = CCC [3] = eee)$list 2=Array("Tao", "Shi", "Han");Sort($list 2);Print_r($list 2);//output Array ([0] = [1] = [2] = tao)$list 3=Array("AAA", "C", "BB", "eeee");Usort($list 3, "Strcomparator");Print_r($list 3);//output Array ([0] = c [1] = BB [2] = = AAA [3] = eeee)//Custom comparison functionfunctionStrcomparator ($a,$b){ if(strlen($a) >strlen($b)){ return1; }ElseIf(strlen($a) <strlen($b)){ return-1; } return0;}
[Javase] Collection Tool Class (Collections-sort)