Java Common Class (v) Collection Tool class collections

Source: Internet
Author: User
Tags addall shuffle sorts

Objective

Java provides a tool class for manipulating set, list, and map collections: Collections, a tool class that provides a number of ways to sort, query, and modify collections.

It also provides methods for placing the collection object immutable, synchronizing control of the collection object, and so on.

This class does not need to create objects, and internally provides static methods.

I. Overview of Collectios

  

Description in the API:

    

Second, the sort operation 2.1, method

1) static void reverse (list<?> List):

Reverses the order of the elements in the list.

2) static void Shuffle (List<?> List):

Randomly sorts the elements of a list collection.

3) static void sort (list<t> List)

Sorts the specified list in ascending order based on the natural ordering of the elements
4) static <T> void sort (list<t> List, comparator<? Super t> C):

Sorts the specified list according to the order produced by the specified comparer.
5) static void swap (list<?> List, int i, int j)

Swaps the element at the specified position i,j the specified list.

6) static void rotate (list<?> List, int distance)

When distance is positive, the distance element "whole" of the list collection is moved to the front, and when distance is negative, the first distance element of the list collection is moved to the rear. The method does not change the length of the collection.

2.2. Instance using sort operation
import Java.util.arraylist;import java.util.Collections; Public classCollectionstest { Public Static voidMain (string[] args) {ArrayList list=NewArrayList (); List.add (3); List.add (-2); List.add (9); List.add (5); List.add (-1); List.add (6); //output: [3,-2, 9, 5,-1, 6]System. out. println (list); //reverse order of collection elementscollections.reverse (list); //output: [6,-1, 5, 9,-2, 3]System. out. println (list); //sort: Sort in ascending orderCollections.sort (list); //[-2,-1, 3, 5, 6, 9]System. out. println (list); //Exchange according to subscriptCollections.swap (list,2,5); //output: [-2,-1, 9, 5, 6, 3]System. out. println (list); /*//Random sort collections.shuffle (list); The order of each output is not fixed System.out.println (list);*/                //move the latter two whole to the frontCollections.rotate (list,2); //output: [6, 9,-2,-1, 3, 5]System. out. println (list); }}
Third, find, replace Operation 3.1, method

1) Static <T> int BinarySearch (list<? extends Comparable<? Super t>> List, T key)

Use the binary search method to search the specified list for the index of the specified object in the list collection.

Note: It is important to ensure that the elements in the list collection are already in an orderly state.

2) static Object max (Collection coll)

Returns the largest element of a given collection, based on the natural order of the elements.

3) static Object max (Collection coll,comparator comp):

Returns the largest element of a given collection, based on the order produced by the specified comparer.

4) Static Object min (Collection coll):

Returns the smallest element of a given collection, based on the natural order of the elements.

5) Static Object min (Collection coll,comparator comp):

Returns the smallest element of a given collection, based on the order produced by the specified comparer.

6) Static <T> void Fill (list<? super t> List, T obj):

Replaces all elements in the specified list with the specified element.
7) static int frequency (collection<?> c, Object O)

Returns the number of occurrences in the specified collection that are equal to the specified object.
8) static int indexofsublist (list<?> source, list<?> target):

Returns the starting position of the specified target list for the first occurrence in the specified source list, or 1 if no such list appears.
9) static int lastindexofsublist (list<?> source, list<?> Target)

Returns the starting position of the specified target list in the specified source list, or 1 if no such list appears.
Static <T> Boolean replaceall (list<t> List, T oldval, T newval)

Replaces all old values of the list object with a new value oldval

3.2. Instance use Find, replace operation
import Java.util.arraylist;import java.util.Collections; Public classCollectionsTest1 { Public Static voidMain (string[] args) {ArrayList list=NewArrayList (); List.add (3); List.add (-2); List.add (9); List.add (5); List.add (-1); List.add (6); //[3,-2, 9, 5,-1, 6]System. out. println (list); //Output Maximum element 9System. out. println (Collections.max (list)); //minimum output element: -2System. out. println (Collections.min (list)); //Replace the 2 in list with aSystem. out. println (Collections.replaceall (list,-2,1)); //[3, 1, 9, 5,-1, 6]System. out. println (list); List.add (9); //determines the number of occurrences of 9 in the collection, returning 2System. out. println (Collections.frequency (list,9)); //to sort a collectionCollections.sort (list); //[-1, 1, 3, 5, 6, 9, 9]System. out. println (list); //only the sorted list collection can be queried using the binary method, output 2System. out. println (Collections.binarysearch (list,3)); }}
Four, synchronous control

Collectons provides multiple synchronizedxxx () methods that can wrap a specified collection as a collection of thread synchronizations to resolve thread-safety issues when multithreading concurrently accesses a collection .

As described earlier, the Hashset,treeset,arraylist,linkedlist,hashmap,treemap are thread insecure. Collections provides multiple static methods that can wrap them up as a collection of thread synchronizations.

4.1. Methods

1) Static <T> collection<t> synchronizedcollection (collection<t> c)

Returns the synchronization (thread-safe) collection that the specified collection supports.
2) Static <T> list<t> synchronizedlist (list<t> List)

Returns a list of synchronized (thread-safe) support for the specified list.
3) Static <K,V> map<k,v> Synchronizedmap (map<k,v> m)

Returns the synchronized (thread-safe) mappings supported by the specified mappings.
4) Static <T> set<t> Synchronizedset (set<t> s)

Returns the synchronous (thread-safe) set supported by the specified set.

4.2. Example
Import java.util.*;  Public classtestsynchronized{ Public Static voidMain (string[] args) {//The following program creates four synchronized collection objectsCollection C = collections.synchronizedcollection (NewArrayList ()); List List= Collections.synchronizedlist (NewArrayList ()); Set s= Collections.synchronizedset (NewHashSet ()); Map m= Collections.synchronizedmap (NewHashMap ()); }} 
V. Collesction setting immutable set 5.1, method

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 only the specified object (only one or one element), where the collection can be: List,set,map.

3) unmodifiablexxx ():

Returns the immutable view of the specified collection object, where the collection can be: List,set,map.

The parameters of the above three types of methods are the original collection objects, and the return value is the "read only" version of the collection.

5.2. Example
Import java.util.*;  Public classtestunmodifiable{ Public Static voidMain (string[] args) {//create an empty, immutable list objectList<string> unmodifiablelist =collections.emptylist (); //Unmodifiablelist.add ("Java"); //Add exception occurred: Java.lang.UnsupportedOperationExceptionSystem. out. println (Unmodifiablelist);// []        //Create a set object that has only one element and cannot be changedSet Unmodifiableset = Collections.singleton ("Struts2 authoritative Guide");//[Struts2 authoritative guide]System. out. println (Unmodifiableset); //create a normal map objectMAP scores =NewHashMap (); Scores.put ("language", the); Scores.put ("Java", the); //returns the immutable version corresponding to the normal map objectMap Unmodifiablemap =Collections.unmodifiablemap (scores); //the following line of code throws an Unsupportedoperationexception exceptionUnmodifiablelist.add ("test Element"); Unmodifiableset.add ("test Element"); Unmodifiablemap.put ("language", -); }}
Vi. Other methods 6.1, methods

1) AddAll () method

 Public static <T> boolean addall (collection<? super t> c,t ... elements)?

Adds all the specified elements to the specified collection. You can specify the elements you want to add individually, or specify them as an array. The behavior of this convenient method is the same as that of C.addall (arrays.aslist (elements)) ,

But in most implementations, this method can be much faster to run.

import Java.util.arraylist;import java.util.arrays;import java.util.List; Public classCollectionsTest2 { Public Static voidMain (string[] args) {string[] str={"Hello","Nihao","say"," Love"}; List<String> List1 =arrays.aslist (str); ArrayList List2=NewArrayList ();        List2.addall (List1); System. out. println (LIST2); }}    

Like on the point of a "recommendation" Oh!

Java Common Class (v) Collection Tool class collections

Related Article

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.