Home > Java > javaTutorial > Summary of Java-collections usage code examples

Summary of Java-collections usage code examples

黄舟
Release: 2017-03-15 11:57:48
Original
1484 people have browsed it

What you see on paper is shallow, but you know you have to do it in detail --Lu You Ask the canal how clear it is to have a source of living water --Zhu Xi


# Class Collections is a Packaging category. It contains various staticmultistate methods related to collection operations. This class cannot be instantiated, just like a tool class that serves Java's Collection framework.

java.lang.Object
        java.util.Collections
Copy after login

Commonly used methods in Collections:

( 1) sort() sorting method

FunctionDefinition: public static extends Comparablesuper T>> void sort(List list) root Sort the specified list in ascending order according to the natural order of the elements.

Parameters: The list to be sorted. Function definition:

public static void sort(List list,Comparator c), generated based on the specified comparator Sorts the specified list in order. All elements within this list must be comparable to each other using the specified comparator.

Parameters: list-the list to be sorted; c-the comparator that determines the order of the list. (2) binarySearch()

Binary search

Method

Function definition: public static int binarySearch (List> list,T key)

Use the binary search method to search the specified list to obtain the specified object. Before calling this method, the list elements must be sorted in ascending order, otherwise the result is uncertain , this method will perform O(n) link traversals and O(log n) element comparisons.

Parameters: list-the linked list to be searched, key-the key to be searched.

Function definition: public static int binarySearch(List list, T key, Comparator c) Sort the list in ascending order according to the specified comparator.

Parameters: list-the list to be searched, key-the key to be searched, c-the comparator of the sorted list.

(3) reverse() reverse method

#Number definition: public static void reverse(List list), reverses the order of elements in the specified list. This method runs in linear time.

Parameters: list-the list whose elements are to be reversed

(4) shuffle() shuffling method

Functionnumber definition:public static void shuffle(List list) uses the default random source to replace the specified list. The probability of all replacements occurring is approximately equal.

Parameters: list-the list to be reorganized

## Function

numberDefinition:public static void shuffle(List list,Random rnd), uses the specified random source to replace the specified list.

Parameters: list-the list to be shuffled, rnd-the random source used to shuffle the list.

(5) swap() exchange method

Function definition: public static void swap(List list,int i, int j), exchange elements at the specified position in the specified list.

Parameters: list-the list for element exchange, i-the index of one element to be exchanged, j-the other element to be exchanged The index of an element.

(6) fill() replacement method

Function definition: public static void fill(List list,T obj), replaces all elements in the specified list with the specified element, running in linear time.

Parameters: list - a list filled with specified elements, obj - the elements used to fill the specified list.

(7)copy()Copy method

Function definition: public static void copy(List dest,List src), copies all elements from one list to another. After doing this, the index of each copied element in the destination list will be equal to the index of that element in the source list, and the destination list must be at least as long as the source list.

Parameters: dest-dest list, src-source list.

(8) min() minimum value method

Function definition: public static > T min(Collection coll), returns the smallest element of the given Collection according to the natural order of the elements. All elements in the Collection must implement Comparable Interface, In addition, all elements in the collection must be comparable to each other.

Parameters: coll - the collection whose smallest element will be determined.

Function definition: public static T min(Collection coll,Comparator comp), returns the smallest element of the given collection according to the order generated by the specified comparator.

Parameters: coll-the collection whose minimum element will be determined, comp-the comparator used to determine the minimum element.

(9) max() maximum value method

Function definition: public static > T max(Collection coll), returns the largest element of the given collection according to the natural order of the elements.

Parameters: coll - the collection whose largest element will be determined.

Function definition: public static T max(Collection< ?extends T> coll,Comparator comp), returns the largest element of the given collection according to the order generated by the specified comparator.

Parameters: coll-the collection whose largest element will be determined, comp-the comparator used to determine the largest element

(10)rotate() rotation method

Function definition: public static void rotate(List list, int distance), rotates the elements in the specified list according to the specified distance.

Parameters: list-the list to be rotated, distance-the distance for list rotation, which can be 0, a negative number, or a number greater than list.size().

(11)replaceAll()Replace all functions

        函数定义:public static boolean replaceAll(List list,T oldVal,newVal),使用另一个值替换列表总出现的所有的某一指定值。

        参数:list-在其中进行替换的列表;oldVal-将被替换的原值;newVal-替换oldVald的新值。


示例代码:

public class Hello {
public static void main(String[] args) {
        System.out.println("sort");
        List list=new ArrayList<Double>();
       double array[] = {112, 111, 23, 456, 231 };
        for (int i = 0; i < array.length; i++) {
            list.add(new Double(array[i]));
        }
        Collections.sort(list);//自然排序
        for (int i = 0; i < array.length; i++) {
            System.out.println(list.get(i));
        }
        System.out.println("shuffle");

        Collections.shuffle(list);//置换
        for (int i = 0; i < array.length; i++) {
            System.out.println(list.get(i));
        }
        Collections.sort(list);//自然排序
        System.out.println("reverse");
        Collections. reverse (list);//反转
        for (int i = 0; i < array.length; i++) {
            System.out.println(list.get(i));
        }
        Collections.sort(list);//自然排序
        System.out.println("copy");
        List li = new ArrayList();
        double arr[] = {1131,333};
        for(int j=0;j<arr.length;j++){
            li.add(new Double(arr[j]));
        }
        Collections.copy(list,li);//拷贝
        for (int i = 0; i <list.size(); i++) {
            System.out.println(list.get(i));
        }
        System.out.println("min");
        System.out.println(Collections.min(list));//返回最小值
        System.out.println("max");
        System.out.println(Collections.max(list));//返回最大值
        System.out.println("rotate");
        Collections.rotate(list,-1);//循环
        for (int i = 0; i <list.size(); i++) {
            System.out.println( list.get(i));
        }
         System.out.println("binarySearch");
        Collections.sort(list);
        System.out.println(list);
        System.out.println(Collections.binarySearch(list, 333.0));//二分查找
    }
}
Copy after login

以上是Collections比较常用的方法,Collections还有很多其他的方法,如下表:


##static##staticbinarySearch##static##staticcheckedMap##static (Set s, Class type)##staticcopy##static boolean##static# #emptySet##static Enumeration(Collection c)static int##lastIndexOfSubList##staticmax##static T> T                                                                                                                                                                                                                                                                          returned the smallest element of the given collection according to their natural order. ##static##staticnewSetFromMap##static boolean(List list, T oldVal, T newVal)##static##staticreverseOrder##static void##static void#shuffle##static<T> Set<T><T> List<T>                Returns an immutable list containing only the specified objects. ##static##static void(List< ;?> list, int i, int j)##static##static(Set s)##staticunmodifiableCollection##static<T> List<T>(List list)##staticunmodifiableSortedMap##static<T> SortedSet<T> ## Return to a specified unmodified view of orderly SET.
MethodSummary
## static boolean addAll<span style="background-color:inherit; color:rgb(51,51,51)">(Collection<? super T> c, T...elements)</span> Add all specified elements to the specified collection.
##static<T> Queue<T> asLif<span style="background-color:inherit; color:rgb(51,51,51)">oQueue<a href="http://www.php.cn/wiki/109.html" target="_blank">(Deque<T> deque)</a> </span>                                                                                                            Return the view
of a certain Deque in the form of last-in-first-out (Lifo) Queue.
int binarySearch(List> list, T key) <span style="background-color:inherit; color:rgb(51,51,51)"> Use binary search method to search the specified list to obtain the specified object. </span>
int (List list, T key, Comparator c) Use binary search to search the specified list to obtain the specified object.
##static Collection # #checkedCollection(Collection<E> c, Class<E> type)<span style="background-color:inherit; color:rgb(51,51,51)"> </span>                                                                                                                                                                                                  can be returned to a dynamically typed safe
view of the specified collection.
List checkedList<span style="background-color:inherit; color:rgb(51,51,51)">(List<E> list, Class<E> type)<a href="http://www.php.cn/wiki/596.html" target="_blank"> </a> Returns a dynamic type-safe view of the specified list. </span>
<K,V> Map<K,V> (Map<K,V> m, Class keyType, Class valueType)                                                                                                                                                                             Returns a dynamic type-safe view of the specified mapping. <span style="background-color:inherit; color:rgb(51,51,51)"></span>
SetcheckedSet                 Returns a dynamically type-safe view of the specified set.
##static<K,V> SortedMap<K,V> checkedSortedMap(SortedMap<K,V> m, Class keyType, Class valueType)                             Returns a dynamic type-safe view of the specified ordered mapping.
##static<E> SortedSet<E> # #checkedSortedSet(SortedSet s, Class type) <span style="background-color:inherit; color:rgb(51,51,51)">                                                     Returns a dynamic type-safe view of the specified ordered set. </span>
void (List dest, List src) Copies all elements from one list to another. <span style="background-color:inherit; color:rgb(51,51,51)"></span>
##disjoint(Collection< ;?> c1, Collection c2) If there are no identical elements in the two specified collections, true is returned.
##static<T> List<T> emptyList<span style="background-color:inherit; color:rgb(51,51,51)">()</span> Returns an empty list (immutable).
##static<K,V> Map<K,V> emptyMap()<span style="background-color:inherit; color:rgb(51,51,51)"> </span> Returns an empty map (immutable).
<T> Set<T>() Returns an empty set (immutable). <span style="background-color:inherit; color:rgb(51,51,51)"></span>
enumeration                Returns an enumeration over the specified collection.
##static void fill<span style="background-color:inherit; color:rgb(51,51,51)">(List<? super T> list, T obj)</span> Replaces all elements in the specified list with the specified element.
static int ##frequency(Collection&lt ;?> c, Object o)<span style="background-color:inherit; color:rgb(51,51,51)"> </span> Returns the number of elements in the specified collection that are equal to the specified object.
static int ##indexOfSubList(List< ;?> source, List target) <span style="background-color:inherit; color:rgb(51,51,51)">                                                                                                                                                                                                                                                                                out out can be returned. </span>
(List< ;?> source, List target) Returns the starting position of the last occurrence of the specified target list in the specified source list; if no such list appears, returns -1.
##static ArrayList list<span style="background-color:inherit; color:rgb(51,51,51)">(Enumeration<T> e)</span>                                                                                                           can be returned.
> T (Collection According to the element of the <span style="background-color:inherit; color:rgb(51,51,51)"> Natural Sequence </span>, return to the greatest element of given by given.
##max(Collection According to the order generated by the specified comparator, return the greatest element of given collection. <span style="background-color:inherit; color:rgb(51,51,51)"></span>
##static
min(Collection coll)
##static T ##min(Collection<? extends T & GT; color, comparator & lt ;? Super T & GT; Comp) <span style="background-color:inherit; color:rgb(51,51,51)"> </span> According to the order generated by the specified comparator, return the minimum element of given together.
<T> List<T> nCopies(int n, T o) <span style="background-color:inherit; color:rgb(51,51,51)">          Returns an immutable list consisting of </span>n copies of the specified object.
Set (Map map)                         Returns the set supported by the specified mapping. <span style="background-color:inherit; color:rgb(51,51,51)"></span>
replaceAll Replaces all occurrences of a specified value in a list with another value.
##static void ##reverse(List&lt ;?> list)<span style="background-color:inherit; color:rgb(51,51,51)"> </span> Reverse the order of elements in the specified list.
Comparator reverseOrder() <span style="background-color:inherit; color:rgb(51,51,51)"> Returns a comparator that forcibly reverses the </span>natural order of a collection of objects that implements the
Comparable interface.
Comparator (Comparator cmp) Returns a comparator that forcibly reverses the order of the specified comparator. <span style="background-color:inherit; color:rgb(51,51,51)"></span>
#rotate(List< ;?> list, int distance) Rotates the elements in the specified list according to the specified distance.
##static void #shuffle(List&lt ;?> list)<span style="background-color:inherit; color:rgb(51,51,51)"> </span> Use the default random source to replace the specified list.
(List< ;?> list, Random rnd) Use the specified random source to replace the specified list. <span style="background-color:inherit; color:rgb(51,51,51)"></span>
# #singleton(T o) Returns an immutable set containing only the specified object. <span style="background-color:inherit; color:rgb(51,51,51)"></span>
##static
singletonList(T o)
##static<K,V> Map<K,V> singletonMap<span style="background-color:inherit; color:rgb(51,51,51)">(K key, V value)</span> Returns an immutable map that only maps the specified key to the specified value.
##static<T extends Comparable<? super T>> void sort(List<T> list)<span style="background-color:inherit; color:rgb(51,51,51)"> </span>         Sort the specified list in ascending order according to the natural order
of the elements.
void sort(List list, Comparator c) <span style="background-color:inherit; color:rgb(51,51,51)"> Sorts the specified list according to the order produced by the specified comparator. </span>
##swap                                                                                                                                                         will swap elements at the specified positions in the specified list.
##static Collection syn<span style="background-color:inherit; color:rgb(51,51,51)">chr<a href="http://www.php.cn/wiki/1332.html" target="_blank">onizedCollection</a>(Collection<T> c)</span>                                                                                                                                           Returns a synchronized (thread-safe) collection supported by the specified collection.
##static<T> List<T> synchronizedList(List<T> list)<span style="background-color:inherit; color:rgb(51,51,51)"> </span> Returns a synchronized (thread-safe) list supported by the specified list.
<K,V> Map<K,V> synchronizedMap(Map<K,V> m) <span style="background-color:inherit; color:rgb(51,51,51)"> Returns a synchronized (thread-safe) map backed by the specified map. </span>
<T> Set<T># #synchronizedSet                                           Returns a synchronous (thread-safe) set supported by the specified set.
##static<K,V> SortedMap<K,V> synchronizedSortedMap(SortedMap<K,V> m)                                                                                                                                                                                                                                                         returned.
##static<T> SortedSet<T> # #synchronizedSortedSet(SortedSet s) <span style="background-color:inherit; color:rgb(51,51,51)">                                                                                                                                Returns a synchronized (thread-safe) ordered set supported by the specified ordered set. </span>
Collection (Collection c) Returns an unmodifiable view of the specified collection. <span style="background-color:inherit; color:rgb(51,51,51)"></span>
unmodifiableList                Returns an unmodifiable view of the specified list.
##static<K,V> Map<K,V> unmodifiableMap<span style="background-color:inherit; color:rgb(51,51,51)">(Map<? Extends K ,? Extends v & GT; M) </span> Return to the non -modified view of specified mapping.
##static<T> Set<T> # #unmodifiableSet(Set s) <span style="background-color:inherit; color:rgb(51,51,51)">                                                                                                                                                               Returns the unmodifiable view of the specified set. </span>
<K,V> SortedMap<K,V> (SortedMap m)                         Returns an unmodifiable view of the specified ordered map. <span style="background-color:inherit; color:rgb(51,51,51)"></span>
# #UnmodiFiablesortedSet (SortedSet & LT; T & GT; S) <span style="background-color:inherit; color:rgb(51,51,51)"></span>

The above is the detailed content of Summary of Java-collections usage code examples. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template