Collections can sort the elements that store the basic wrapper class for ArrayList and store custom objects?
Custom objects to sort by writing their own comparators
1 packagecn.itcast_02;2 3 Importjava.util.ArrayList;4 Importjava.util.Collections;5 Importjava.util.Comparator;6 Importjava.util.List;7 public classCollectionsdemo {8 public Static voidmain (string[] Args) {9 //to Create a Collection objectTenlist<student> list =NewArraylist<student>(); one a //Create student Objects -Student S1 =NewStudent ("brigitte", 27); -Student s2 =NewStudent ("wind qing", 30); theStudent s3 =NewStudent ("lynn qu", 28); -Student S4 =NewStudent ("Wu Xin", 29); -Student S5 =NewStudent ("brigitte", 27); - + //Adding an Element object - List.add (s1); + List.add (s2); a List.add (s3); at List.add (s4); - List.add (s5); - - //Sort - //Natural Sort - //Collections.sort (list); in //Comparator Sort - //If you have both a natural sort and a comparator sort, the comparator is sorted primarily toCollections.sort (list,NewComparator<student>() { + @Override - public intCompare (Student s1, Student s2) { the intnum = S2.getage ()-s1.getage (); * intnum2 = num = = 0?s1.getname (). compareTo (s2.getname ()) $ : num;Panax Notoginseng returnnum2; - } the }); + a //iterating through the collection the for(Student S:list) { +System.out.println (s.getname () + "---" +s.getage ()); - } $ } $}
Java 18-11 collections used in ArrayList collection