JDK source code analysis of Java.util.Collections

java.util.Collections is a wrapper class. It contains various static polymorphic methods related to set operations . Such can not be instantiated , like a tool in class service to the Java Collection Framework.

One, source code analysis

1. Not instantiable

  	private Collections() {
    
    }

CollectionsIt is a non-instantiable class in the util package.

2. Optimize parameters

    private static final int BINARYSEARCH_THRESHOLD   = 5000;
    private static final int REVERSE_THRESHOLD        =   18;
    private static final int SHUFFLE_THRESHOLD        =    5;
    private static final int FILL_THRESHOLD           =   25;
    private static final int ROTATE_THRESHOLD         =  100;
    private static final int COPY_THRESHOLD           =   10;
    private static final int REPLACEALL_THRESHOLD     =   11;
    private static final int INDEXOFSUBLIST_THRESHOLD =   35;

These variables defined by Collecions are called tuning parameters, and their role is to optimize the performance of methods in the class.

3. Sort function sort()

3.1. Sort the specified list in ascending order according to the natural order of the elements
    @SuppressWarnings("unchecked")
    public static <T extends Comparable<? super T>> void sort(List<T> list) {
    
    
        list.sort(null);
    }

Parameters: The list to be sorted.

3.2. Sort the specified list according to the order generated by the specified comparator. All elements in this list must be comparable to each other using the specified comparator.
    @SuppressWarnings({
    
    "unchecked", "rawtypes"})
    public static <T> void sort(List<T> list, Comparator<? super T> c) {
    
    
        list.sort(c);
    }

Parameters: list-list to be sorted; c-comparator to determine the order of the list.

3.3. About the list.sort method
List.sort is a method added by JDK in 1.8
@SuppressWarnings({
    
    "unchecked", "rawtypes"})
    default void sort(Comparator<? super E> c) {
    
    
        Object[] a = this.toArray();
        Arrays.sort(a, (Comparator) c);
        ListIterator<E> i = this.listIterator();
        for (Object e : a) {
    
    
            i.next();
            i.set((E) e);
        }
    }

First, pass in a comparator as a parameter, then convert the list into an array, and then sort the array. After sorting, use the iterator to change the list again.

4. Binary search method binarySearch()

There are many binarySearch and related methods in Collection, here only two representative ones are selected

4.1. Use the binary search method to search the specified list to obtain the specified object. Before calling this method, the list elements should be sorted in ascending order, otherwise the result is uncertain. This method will perform O(n) link traversal and O(log n) Sub-element comparison.
    public static <T> int binarySearch(List<? extends Comparable<? super T>> list, T key) {
    
    
        if (list instanceof RandomAccess || list.size()<BINARYSEARCH_THRESHOLD)
            return Collections.indexedBinarySearch(list, key);
        else
            return Collections.iteratorBinarySearch(list, key);
    }

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

4.2. Sort the list in ascending order according to the specified comparator.
    public static <T> int binarySearch(List<? extends T> list, T key, Comparator<? super T> c) {
        if (c==null)
            return binarySearch((List<? extends Comparable<? super T>>) list, key);

        if (list instanceof RandomAccess || list.size()<BINARYSEARCH_THRESHOLD)
            return Collections.indexedBinarySearch(list, key, c);
        else
            return Collections.iteratorBinarySearch(list, key, c);
    }

Parameters: list-list to search, key-key to search, c-comparator for sorting list.

5. Reverse method reverse()

Turn the order of the elements in the specified list, this method runs in linear time.

@SuppressWarnings({
    
    "rawtypes", "unchecked"})
public static void reverse(List<?> list) {
    
    
    int size = list.size();
    if (size < REVERSE_THRESHOLD || list instanceof RandomAccess) {
    
    
        for (int i=0, mid=size>>1, j=size-1; i<mid; i++, j--)
            swap(list, i, j);
    } else {
    
    
        // instead of using a raw type here, it's possible to capture
        // the wildcard but it will require a call to a supplementary
        // private method
        ListIterator fwd = list.listIterator();
        ListIterator rev = list.listIterator(size);
        for (int i=0, mid=list.size()>>1; i<mid; i++) {
    
    
            Object tmp = fwd.next();
            fwd.set(rev.previous());
            rev.set(tmp);
        }
    }
}

​ Parameters: list- the list of elements to be reversed

6, shuffle method shuffle()

6.1. Use the default random source to replace the specified list, and the probability of all replacements is roughly equal
    public static void shuffle(List<?> list) {
    
    
        Random rnd = r;
        if (rnd == null)
            r = rnd = new Random(); // harmless race.
        shuffle(list, rnd);
    }

Parameters: list-list to be reorganized

6.2. Replace the specified list with the specified random source
@SuppressWarnings({
    
    "rawtypes", "unchecked"})
public static void shuffle(List<?> list, Random rnd) {
    
    
    int size = list.size();
    if (size < SHUFFLE_THRESHOLD || list instanceof RandomAccess) {
    
    
        for (int i=size; i>1; i--)
            swap(list, i-1, rnd.nextInt(i));
    } else {
    
    
        Object[] arr = list.toArray();

        // Shuffle array
        for (int i=size; i>1; i--)
            swap(arr, i-1, rnd.nextInt(i));

        // Dump array back into list
        // instead of using a raw type here, it's possible to capture
        // the wildcard but it will require a call to a supplementary
        // private method
        ListIterator it = list.listIterator();
        for (int i=0; i<arr.length; i++) {
    
    
            it.next();
            it.set(arr[i]);
        }
    }
}

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

7. Other main methods

7.1, the exchange method swap()
  • ​ Function definition: public static void swap(List<?> list,int i,int j)
  • ​ Exchange elements at the specified position in the specified list.
  • ​ Parameters: list-list for element exchange, i-index of an element to be exchanged, j-index of another element to be exchanged.
7.2. Replacement method fill()
  • ​ Function definition: public static void fill(List<? super T> list,T obj)
  • ​ Replace all elements in the specified list with the specified element, and run in linear time.
  • ​ Parameters: list- use the specified element to fill the list, obj- used to fill the specified list of elements.
7.3, copy method copy()
  • ​ 函数定义:public static void copy(List<? super T> dest,List<? extends T> src)
  • ​ Copy all elements from one list to another list. After performing this operation, the index of each copied element in the target list will be equal to the index of the element in the source list, and the length of the target list must be at least equal to the source list.
  • ​ Parameters: dest-target list, src-source list.
7.4, minimum method min()
  • ​ 函数定义:public static <T extends Object & Comparable<? super T>> T min(Collection<? extends T> coll)

  • ​ Returns the smallest element of a given Collection according to the natural order of the elements. All elements in the Collection must implement the Comparable interface. In addition, all elements in the collection must be mutually comparable.

  • ​ Parameters: coll- will determine the collection of its smallest element.

  • ​ Function definition: public static T min(Collection<? extends T> coll,Comparator<? super T> comp)

  • ​ Returns the smallest element of the given collection according to the order produced by the specified comparator.

  • ​ Parameters: coll- will determine the collection of its smallest element, comp- the comparator used to determine the smallest element.

7.5, the maximum value method max()
  • ​ 函数定义:public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll)
  • ​ According to the natural order of the elements, returns the largest element of the given collection.
  • ​ Parameters: coll- The collection of the largest element will be determined.
  • ​ 函数定义:public static T max(Collection<?extends T> coll,Comparator<? super T> comp)
  • ​ Returns the largest element of the given collection according to the order produced by the specified comparator.
  • ​ Parameters: coll- will determine the collection of its largest element, comp- the comparator used to determine the largest element
7.6, the rotation method rotate()
  • ​ Function definition: public static void rotate(List<?> list, int distance)
  • ​ Rotate the elements in the specified list according to the specified distance.
  • ​ Parameters: list- the list to be rotated, distance- the distance of the list rotation, which can be 0, negative or larger than list.size().
7.7, replace all functions replaceAll()
  • ​ Function definition: public static boolean replaceAll(List list,T oldVal,T newVal)
  • ​ Replace all the specified values ​​that always appear in the list with another value.
  • ​ Parameters: list-the list in which to replace; oldVal-the original value to be replaced; newVal-the new value to replace oldVald.

Two, the difference between Collection and Collections

1.Collection:

Collection is the upper interface of the collection class. It is an Interface itself, which contains some basic operations of the collection.

Collection interface is the parent interface of Set interface and List interface

2.Collections

Collections is a helper class for the collection framework, which contains some sorting, searching and serialization operations on collections.

Collections is a class,

Collections is a wrapper class, Collection represents a group of objects, these objects are also called collection elements. Some collections allow duplicate elements, while others do not. Some collections are ordered, while others are disordered.

Guess you like

Origin blog.csdn.net/weixin_45187434/article/details/108867294