Java 18-11 collections used in ArrayList collection

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.