Java Collection Framework (vi)--collections tool class

Source: Internet
Author: User
Tags shuffle sorts

    • Tool class for manipulating collections collections

Java provides a tool class for manipulating set, list, and map collections: Collections, which provides a number of ways to sort, query, and modify collection elements, and provides Sets the collection object to immutable, synchronizing control of the collection object, and so on.

    • Sort operations

Collections provides several methods for sorting the list collection elements :

    1. static void reverse (list list); Reverses the order of the specified list collection elements.
    2. static void Shuffle (list list); Randomly sorts the elements of the list collection (the Shuffle method simulates the "Shuffle Action").
    3. static void sort (list list); Sorts the elements of the specified list collection in ascending order, based on the natural ordering of the elements.
    4. static void sort (list list, Comparator C); Sorts the elements of the list collection according to the order in which the specified comparator are produced.
    5. static void Swap (list list, int i, int j); Swaps the I and J elements in the specified list collection.
 Public classTest { Public Static voidMain (string[] args) {List<Integer> list =NewArraylist<integer>(); List.add (2); List.add (1); List.add (4); List.add (9); List.add (13); List.add (11); List.add (12); //print Results [2, 1, 4, 9, A, one, one]System.out.println (list); //1.1 Reverses the order of the specified list collection elements. collections.reverse (list); //printing Results [9, 4, 1, 2]System.out.println (list); //1.2 Random ordering of list collectionscollections.shuffle (list); //Print Results RandomSystem.out.println (list); //1.3 Natural ordering of list collections (small to Large)Collections.sort (list); //printing results for [1, 2, 4, 9, one, one, a.]System.out.println (list); //1.4 Customizing the list collection (in reverse order)Collections.sort (list,NewComparator<integer>() {@Override Public intCompare (integer O1, integer o2) {if(O1 >O2) {                    return-1; }                if(O1 < 02){                    return1; }                return0;        }        }); //printing results for [9, 4, 2, 1]System.out.println (list); //1.5 Swap The position of the element with subscript 0 and subscript 3Collections.swap (list, 0, 3); //printing results for [9, 4, 2, 1]System.out.println (list); }}

    • Find, replace operation

Collections also provides the following common methods for locating and replacing collection elements:

  1. static int BinarySearch (list list, Object key); Searches the specified list collection using the binary search method to obtain the index of the specified object in the list collection. If you want this method to work correctly, you must ensure that the elements in the list are already in an orderly state.
  2. Static Object Max (Collection coll); Returns the largest element in a given set, based on the natural ordering of the elements.
  3. Static Object Max (Collection coll, Comparator comp); Returns the largest element of a given collection, based on the order in which the specified comparator is produced.
  4. Static Object min (Collection coll); Returns the smallest element in a given set, based on the natural ordering of the elements.
  5. Static Object min (Collection coll, Comparator comp); Returns the smallest element of a given set, based on the order in which the specified comparator is produced.
  6. static void Fill (List list, Object obj); Replaces all elements in the specified list collection with obj of the specified element.
  7. static int frequency (Collection c, Object O); Returns the number of elements in the specified element that are equal to the specified object.
  8. static int indexofsublist (list source, list target); Returns the position index of the first occurrence of the list object in the parent list object, or 1 if no such child list appears in the parent list.
  9. static int lastindexofsublist (list source, list target); Returns the position index of the last occurrence of the list object in the parent list object, or 1 if no such child list appears in the parent list.
  10. Static Boolean ReplaceAll (List List, Object Oldval, Object newval); Replaces all old value oldval of the list object with a new value, newval.
 Public classTest { Public Static voidMain (string[] args) {List<Integer> list =NewArraylist<integer>(); List.add (2); List.add (1); List.add (4); List.add (9); List.add (13); List.add (11); List.add (12); //1.1 returns the largest element in the collection based on the natural ordering of the elementsInteger max =Collections.max (list); //Printing ResultsSystem.out.println (max); //To sort a collection naturallyCollections.sort (list); //printed Results [1, 2, 4, 9, one, a, a]System.out.println (list); //1.2 searches the specified list collection using the binary search method to obtain the index of the specified object in the list collection. If you want this method to work correctly, you must ensure that the elements in the list are already in an orderly state.         intBinarySearch = Collections.binarysearch (list, 13); //Printing Results 6System.out.println (BinarySearch); //1.3 Returns the largest element of a given set, based on the order in which the specified comparator is produced. Integer max2 = Collections.max (list,NewComparator<integer>() {@Override Public intCompare (integer O1, integer o2) {if(O1 > O2)return-1; if(O1 < O2)return1; return0;        }        }); //Printing Results 1System.out.println (MAX2); //1.4 Replaces all elements in the specified list collection with 111 of the specified element. Collections.fill (list, 111); //printed Results [111, 111, 111, 111, 111, 111, 111]System.out.println (list); //1.5 Returns the number of elements in the specified element equal to the specified object        intCount = collections.frequency (list, 111); //Printing Results 7System.out.println (count); //2.1 Re-declaration of 2 sets to do the experimentList<integer> List2 =NewArraylist<integer>(); List2.add (1); List2.add (2); List2.add (3); List2.add (4); List2.add (5); List2.add (6); List<Integer> List3 =NewArraylist<integer>(); List3.add (4); List3.add (5); //2.2 Returns the position index of the first occurrence of the list object in the parent list object, or 1 if no such child list appears in the parent list.         intIndexofsublist =collections.indexofsublist (List2, list); //Print Result-1System.out.println (indexofsublist); intIndexOfSubList2 =collections.indexofsublist (List2, LIST3); //Printing Results 3System.out.println (INDEXOFSUBLIST2); //2.4 Replace the 4 in the List3 collection with 9Collections.replaceall (LIST3, 4, 9); //printing Results [9, 5]System.out.println (LIST3); }}
    • Synchronization control

  Several synchronizedxxx methods are available in the collections class that return the synchronization objects corresponding to the specified collection object, which resolves the thread-safety issue when multithreading concurrently accesses the collection.

 Public class Test {    publicstaticvoid  main (string[] args) {        Set<integer > set = Collections.synchronizedset (new hashset<integer>());        List<Integer> list = collections.synchronizedlist (new arraylist<integer>());        Map<integer, string> map = Collections.synchronizedmap (new Hashmap<integer, string> ());    }}
    • Setting immutable Collections

Collections provides the following three methods to return an immutable collection:

    1. Emptyxxx (); Returns an empty, immutable collection object, where the collection can be either a list, a set, or a map.
    2. Singletonxxx (); Returns an immutable collection object that contains the specified object (only one or more elements), where the collection can be either a list, a set, or a map.
    3. Unmodifiablexxx (); Returns an immutable view of the specified object. The collection here can be either a list or a set, or it can be a map.

The parameters of the above three methods are the original collection object, and the return value is the "read only" version of the collection. A "read-only" collection or map can be generated by providing three classes of methods above collections.

 Public classTest { Public Static voidMain (string[] args) {List<Integer> list =collections.emptylist (); Set<Integer> set = Collections.singleton (121); Map<integer, string> tempmap =NewHashmap<integer, string>(); Tempmap.put (1, "one"); Tempmap.put (2, "both"); Tempmap.put (3, "three"); Map<integer, string> UnMap =Collections.unmodifiablemap (TEMPMAP); //the following line of code throws an Unsupportedoperationexception exceptionList.add (33); Set.add (33); Unmap.put ("Four"); }}

Java Collection Framework (vi)--collections tool class

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.