Java Collection Framework 03

Source: Internet
Author: User
Tags collator comparable

Use of the Collections tool class

 Public classNewsImplementsComparable {Private intId//News Number    PrivateString title;//News Headlines@Override PublicString toString () {return"News [number =" + ID + ", title =" + title + "]"; }         PublicNews () {//non-parametric construction        Super(); }     PublicNews (intID, String title) {//with parametric construction        Super();  This. ID =ID;  This. title =title; }     Public intgetId () {returnID; }     Public voidSetId (intID) { This. ID =ID; }     PublicString GetTitle () {returntitle; }     Public voidSettitle (String title) { This. title =title; }    //override sorted rule ascending@Override Public intcompareTo (Object o) {News news=(News) o; if(News.getid () = = This. ID) {            return0; }Else if(News.getid () < This. ID) {            return1;//descending return-1;}Else {            return-1;//descending return 1;        }    }}

To create a test class

 Public classCollectionstest { Public Static voidMain (string[] args) {/** Tool class for operation set collections **/        //Create a collectionList<string> list=NewArraylist<string>(); List.add ("B"); List.add ("D"); List.add (C); List.add (A); System.out.println ("no sort = =" +list);//Order of insertion time//to randomly sort a collectioncollections.shuffle (list); //Draw number 136 order must be 631 wrongSystem.out.println ("random sort = = =" +)list); //in ascending order of lettersCollections.sort (list); System.out.println ("Ascending = =" +list); //descending also must be after ascendingcollections.reverse (list); System.out.println ("Descending = =" +list); //The position of the query "B" in the collection must be sorted in ascending order before queryingCollections.sort (list); System.out.println (Collections.binarysearch (list,A)); System.out.println ("****************************"); List<News> news=NewArraylist<news> ();//want to implement the sorting of objectsNews.add (NewNews (3, "News 3")); News.add (NewNews (1, "News 1")); News.add (NewNews (4, "News 4")); News.add (NewNews (2, "News 2"));  for(News news2:news) {System.out.println (NEWS2); }        /** If news does not rewrite the comparable interface in the CompareTo () is compiled error! * We must rewrite CompareTo () to define the rules*/Collections.sort (News); System.out.println ("After the object is sorted ...");  for(News news2:news) {System.out.println (NEWS2); }} @Test Public  voidtest1 () {//Convert a string to a string array by using split () in the String classString[] str1= "A b c D D d". Split (""); //convert an array to a collectionList<string> aslist =arrays.aslist (STR1);        System.out.println (aslist); String[] str2= "C D". Split (""); List<String> aslist2=arrays.aslist (STR2); //last occurrence of positionSystem.out.println (Collections.lastindexofsublist (Aslist, asList2)); //first occurrence of positionSystem.out.println (Collections.indexofsublist (Aslist, asList2)); } @Test Public  voidtest2 () {string[] str1= "A b c D E F". Split (""); //convert an array to a collectionlist<string> list =arrays.aslist (STR1);        SYSTEM.OUT.PRINTLN (list); //the elements in the collection move backward distance a position, and then the overridden element loops forwardCollections.rotate (list, 2);    SYSTEM.OUT.PRINTLN (list); }}

Efficiency comparison of 3.MAP traversal

@Test Public  voidTest () {Map<string, object> map=NewHashmap<string, object>();  for(inti = 0; I <1000000; i++) {Map.put ("Key" +i, "value" +i); }       //gets the current number of millisecondsLong a=System.currenttimemillis (); //traverse map to get a collection of all keys firstSet<string> set =Map.keyset ();  for(String key:set) {map.get (key);//get value based on key       }       //gets the current number of millisecondsLong b=System.currenttimemillis (); System.out.println ("The time to traverse with keyset is:" + (B-a)); //use entry to traverse the most efficientset<entry<string, object>> entryset =Map.entryset ();  for(Entry<string, object>Entry:entryset)      {Entry.getvalue (); }      //gets the current number of millisecondsLong c=System.currenttimemillis (); System.out.println ("The time to traverse with EntrySet is:" + (C-b));}

The sorting of Chinese characters

 Public classListtest { Public Static voidMain (string[] args) {//implement the ordering of all Chinese characters into a language environmentComparator<object> collator=collator.getinstance (Locale.china); ArrayList<String> list=NewArraylist<string>(); List.add (Hello); List.add (Good); List.add ("Ah"); List.add ("It's good"); //Tool Classcollections.sort (list, collator);  for(String string:list) {System.out.println (string); }    }}

Java Collection Framework 03

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.