Collection framework | basic use of Java collection framework

Hello, I'm the program ape pony, the hupiao family!
Writing an article is a summary of ordinary times and everyone's common learning and progress, so as to code out their dreams as soon as possible 😊

Coordinates: Shanghai on the plane

1. Understanding and benefits of collections

Collection framework: a container for storing data.

Collection framework is a unified standard architecture for representing and operating collections.
Any set framework contains three parts: external interface, interface implementation and set operation algorithm.

Interface: represents the abstract data type of a collection. The interface allows us to operate a collection without paying attention to the specific implementation, so as to achieve "polymorphism". In object-oriented programming languages, interfaces are often used to form specifications.

Implementation: the specific implementation of the collection interface, which is a highly reusable data structure.

Algorithm: a method to complete some useful calculation on an object that implements the interface in a collection framework, such as search, sorting, etc. These algorithms are usually polymorphic because the same method can behave differently when the same interface is implemented by multiple classes. In fact, the algorithm is a reusable function.
It reduces the effort of programming.

The above is a collection of some concepts. In fact, pony thinks you can just remember the following characteristics

  • You can dynamically save any number of objects, which is more convenient to use!
  • It provides a series of convenient methods to manipulate objects: add, remove, set, get, etc
  • Use the collection to add and delete the schematic code of new elements - concise
  • The collection can be easily extended or rewritten to improve code reusability and operability.
  • By using the JDK's own collection classes, you can reduce the cost of code maintenance and learning new API s.

Framework system of collection


Note: This is not all, but some collections commonly used in daily development. The most commonly used are ArrayList and HashMap

2. Single column Collection

  • There are many methods, which are abstract and need subclasses to implement
  • collection can store multiple elements, and each element can be an Object
  • Some Collection implementation classes can store duplicate elements, while others cannot
  • Some Collection implementation classes are ordered, while others are not
  • The Collection interface does not directly implement subclasses. It is sufficient to implement Collection through its sub interfaces Set and List
    • List: ordered (the order in which the elements are stored in the set is the same as the order in which they are taken out), and the elements have indexes. Elements can be repeated.
    • Set: out of order (the order of storage and retrieval may be inconsistent), and duplicate elements cannot be stored. Element uniqueness must be guaranteed.

The common methods of Collection are not cited here, because its subclasses are used to complete the foundation in daily development (the subclasses will describe the use of its methods in detail below), and its traversal method is described below

Traversal method of Collection:

  1. Iterator (iterator)

    Code demonstration:
        Collection col = new ArrayList();
        col.add(new Book("Romance of the Three Kingdoms", "Luo Guanzhong",10.1));
        col.add(new Book("knife man ", "Gulong",5.1));
        col.add(new Book("The Dream of Red Mansion", "Cao Xueqin",34.6));
        col.add(new Book("100000 why", "nameless",16.7));

        Iterator iterator = col.iterator();
        while(iterator.hasNext()) { //Determine whether there is another object
            //Object compile type object run type Book
            Book book = (Book)iterator.next(); //1. Cause the iterator pointer to move down and return the object it points to
            System.out.println(book);
        }
  1. for loop enhancement


Code demonstration:

        Collection col = new ArrayList();
        col.add(new Book("Romance of the Three Kingdoms", "Luo Guanzhong",10.1));
        col.add(new Book("knife man ", "Gulong",5.1));
        col.add(new Book("The Dream of Red Mansion", "Cao Xueqin",34.6));
        col.add(new Book("100000 why", "nameless",16.7));

        for (Object o : col) {
            System.out.println(o);
        }

2.1 List

sketch:

  1. The elements in the List collection class are orderly (i.e. the addition order is consistent with the extraction order) and repeatable
  2. Each element in the List collection has its corresponding sequential index, that is, it supports index.
  3. The elements in the List container correspond to an integer serial number, recording their position in the container. The elements in the container can be accessed according to the serial number.
  4. Common implementation classes of List interface in JDK API include ArrayList, Vector and LinkedList

Code demonstration for validation 1 and 2:

        List list = new ArrayList();
        list.add("half-and-half");
        list.add("smile");
        list.add("meiko");
        list.add("factory manager");
        list.add("factory manager");
        list.add("The Shy");
        System.out.println(list);

        System.out.println(list.get(1));// smile
        System.out.println(list.get(4));// factory manager

Common methods:

apiexplain
void add(int index, Object ele)Insert the ele element at the index position
boolean addAll(int index, Collection eles)Add all elements in eles from the index position
Object get(int index)Gets the element at the specified index location
int indexOf(Object obj)Returns the position where obj first appears in the collection
int lastIndexOf(Object obj)Returns the last occurrence of obj in the current collection
Object remove(int index)Removes the element at the specified index location and returns this element
Object set(int index, Object ele)Setting the element at the specified index position to ele is equivalent to replacing it
List subList(int fromIndex, int toIndex)Returns a subset from fromIndex to toIndex

Code demonstration:

        // Initial value
        List list = new ArrayList();
        list.add("Beijing");
        list.add("Tianjin");
        list.add("Shanghai");
        list.add("Chongqing");

        //1.void add(int index, Object ele): inserts an ele element at the index position
        //Hope to insert Hangzhou after Shanghai
        list.add(3, "Hangzhou");
        System.out.println("list=" + list);// [Beijing, Tianjin, Shanghai, Hangzhou, Chongqing]

        //2.boolean addAll(int index, Collection eles): add all elements in eles from the index position
        Collection c = new ArrayList();
        c.add("half-and-half");
        c.add("Yodel");
        // After Beijing, insert the five five five Kai, Yodel people
        list.addAll(1, c);
        System.out.println("list=" + list); // [Beijing, wuwukai, Yodel, Tianjin, Shanghai, Hangzhou, Chongqing]

        //3.Object get(int index): get the element at the specified index position
        //Hope to get the yodel
        System.out.println(list.get(2));//Yodel

        //4. int indexOf(Object obj): returns the position where obj first appears in the collection. If not, - 1 is returned
        System.out.println("Fifty five position=" + list.indexOf("half-and-half"));//1

        //5. int lastIndexOf(Object obj): returns the last occurrence of obj in the current set. If not, - 1 is returned
        list.add("half-and-half");
        list.add("Foam");
        System.out.println("Last 50 / 50 position=" + list.lastIndexOf("half-and-half"));//7

        //6. Object remove(int index): removes the element at the specified index position and returns this element
        //Want to delete the last fifty fifty
        list.remove(list.lastIndexOf("half-and-half"));
        System.out.println("After deletion list=" + list);//[Beijing, wuwukai, Yodel, Tianjin, Shanghai, Hangzhou, Chongqing]

        //7.Object set(int index, Object ele): set the element at the specified index position to ele, which is equivalent to replacement. If the index is wrong, it will prompt that it is out of range
        //Hope: Yodel changed to Zhixun
        list.set(list.indexOf("Yodel"), "Zhi Xun");
        System.out.println("After modification list=" + list);//[Beijing, wuwukai, Zhixun, Tianjin, Shanghai, Hangzhou, Chongqing, Mozi]

        //8. List subList(int fromIndex, int toIndex): returns the subset from fromIndex to toIndex
        List subList = list.subList(list.indexOf("half-and-half"), list.indexOf("Foam") + 1);
        System.out.println("subList=" + subList);//[wuwukai, Zhixun, Tianjin, Shanghai, Hangzhou, Chongqing, Mozi]

2.1.1 ArrayList

sketch:

  • ArrayList implements the interface of List. The bottom layer is an array and implements variable functions
  • ArrayList implements all operations of List
  • ArrayList can be null and multiple
  • ArrayList implements data storage by arrays
  • ArrayList is basically equivalent to Vector, except that ArrayList is thread unsafe, but its execution efficiency is high

Analysis of underlying operation mechanism of ArrayList:

  1. ArrayList maintains an array of Object type elementData
    transient Object[] elementData;
  2. When creating an object, if a parameterless constructor is used, the initial elementData capacity is 0 (jdk7)
    Yes (10)
  3. When adding elements: first judge whether to expand the capacity. If you need to expand the capacity, call the grow method,
    Otherwise, add the element directly to the appropriate location
  4. If you use a parameterless constructor, if you need to expand the capacity for the first time, expand the capacity
    elementData is 10. If it needs to be expanded again, the expanded elementData is 1.5 times.
  5. If the constructor with the specified capacity capacity is used, the initial elementData capacity is
    Capacity: if capacity expansion is required, the directly expanded elementData is 1.5 times.

Looking at the flow chart summarizing the capacity expansion mechanism at that time, pony summarized it for a long time 🧐 Interested partners can try to catch up with the source code

In summary:

  • If it is a parametric structure, each expansion is 1.5 times
  • If it is a parameterless structure
    • The first expansion is 10
    • 1.5x capacity expansion from the second time

2.1.2 Vector

sketch:

  1. Definition description of Vector class
  2. The vector class implements a gross array of objects [the bottom layer of the vector is also a
    Variable object array] protected Object[] elementData;
  3. Vector is thread synchronous, that is, thread safe. The operation methods of vector class are synchronized
public synchronized E get(int index) {
	 if (index >= elementCount)
	 	throw new ArrayIndexOutOfBoundsException(index);
	 return elementData(index);
 }
  1. In development, ArrayList is mainly used. Only when thread synchronization safety is really required, can it be considered
    Using Vector

Analysis of underlying operation mechanism of Vector:

Since Vector is not used very much in daily life, pony feels that he only needs to remember the concept:

  • If it is a parameterless structure, the default size is 10. After it is full, it will be expanded by twice the size each time
  • If it is a parametric structure, it will be directly expanded by twice the size each time

2.1.3 LinkedList

sketch:

  1. LinkedList implements the characteristics of bidirectional linked list (data structure) and double ended queue
  2. Implements all operations of the List interface
  3. You can add any element (elements can be repeated), including null
  4. Thread is unsafe and synchronization is not implemented

Underlying operating mechanism of LinkedList

  1. The underlying LinkedList maintains a two - way linked list
  2. The LinkedList maintains two attributes, first and last, which point to the first node and the last node respectively
  3. Each Node (Node object) maintains three attributes: prev, next and item. Prev points to the previous Node and next points to the next Node. Finally, the bidirectional linked list is realized
  4. Therefore, the addition and deletion of LinkedList elements are not completed through arrays, which is relatively efficient.

Cases of addition, deletion, modification and query of LinkedList

		//explain
        //1. The underlying LinkedList is implemented using a two-way linked list
        //2. Therefore, its data addition is relatively simple and based on linked list
        //3. Duplicate data can be added in an orderly manner
        LinkedList linkedList = new LinkedList();
        for (int i = 0; i < 5; i++) {
            linkedList.add("Gork" + i);
        }
        System.out.println(linkedList);// [Gork0, Gork1, Gork2, Gork3, Gork4]

        String s = "half-and-half";
        linkedList.add(s);
        linkedList.add(s);
        //ergodic
        for (Object object : linkedList) {
            System.out.print(object + " ");//Gork0 Gork1 Gork2 Gork3 Gork4 50 50 50
        }

        //Delete, according to index
        linkedList.remove(0);
        System.out.println("After deletion=" + linkedList);// [Gork1, Gork2, Gork3, Gork4, 50 / 50, 50 / 50]
        linkedList.remove(s);//Just delete one here and it's over
        System.out.println("After deletion=" + linkedList);// [Gork1, Gork2, Gork3, Gork4, 50 / 50]

        //Modification, set method
        linkedList.set(0, "Lu Benwei");
        System.out.println(linkedList);//[Lu Benwei, Gork2, Gork3, Gork4, 50-50]

        //Method of finding
        //1. Get by index
        Object object = linkedList.get(0);
        System.out.println(object);//Lu Benwei
        //2. Because LinkedList is a two-way linked list, it supports getFirst and getLast to obtain the first and last elements
        System.out.println(linkedList.getFirst());//Lu Benwei
        System.out.println(linkedList.getLast());//half-and-half

        //traversal method 
        //1. Enhance for
        for (Object ob : linkedList) {
            System.out.print(ob + " ");//Lu Benwei Gork2 Gork3 Gork4 fifty five open
        }
        //2. Iterator
        Iterator iterator = linkedList.iterator();
        while (iterator.hasNext()) {
            System.out.print(iterator.next() + " ");//Lu Benwei Gork2 Gork3 Gork4 fifty five open
        }
        //3. Ordinary
        for (int i = 0; i < linkedList.size(); i++) {
            System.out.print(linkedList.get(i) + " ");//Lu Benwei Gork2 Gork3 Gork4 fifty five open
        }

2.1. 4. Differences among ArrayList, LinkedList and Vector

Bottom structureSynchronizationefficiencyCapacity expansion mechanism
ArrayListVariable arrayOut of syncSlow addition and deletion, fast query1.5 times of reference; The default value of no parameter is 10, and the capacity is expanded by 1.5 times for the second time
LinkedListBidirectional linked listOut of syncFast addition and deletion, slow query/
VectorVariable arraysynchronizationSlow addition and deletion, fast query2 times with parameters, 10 by default without parameters, and 2 times for the second expansion

How to select them:

  1. If we have many operations to change, select ArrayList
  2. If we add and delete many operations, select LinkedList
  3. Generally speaking, in the program, 80% - 90% are queries, so ArrayList will be selected in most cases
  4. In a project, it can be selected flexibly according to the business. It is also possible that a module uses ArrayList,
    Another module is LinkedList
  5. Vector is selected only when synchronization is guaranteed, but the frequency used in daily development is relatively low

2.2 Set

sketch:

  1. Out of order (the order of addition and extraction is inconsistent) and there is no index
  2. Duplicate elements (hashCode+equals) are not allowed, so it can contain at most one null
  3. The implementation classes of Set interface in JDK API include:

    Traversal mode of Set interface
  • Since Set has no index, it has only two traversal modes
    • Iterator iterator
    • Enhanced for loop

Code demonstration:

        Set<String> set = new HashSet<>();
        set.add("Gork");
        set.add("half-and-half");
        set.add("half-and-half");// Repeat, I can't join
        set.add("smile");
        set.add(null);
        set.add(null); // Repeat, I can't join


        //ergodic
        //Traversal mode 1 iterator
        Iterator iterator = set.iterator();
        while(iterator.hasNext()) {
            Object object = iterator.next();
            System.out.print(object + " ");// Gork smiles
        }

        //Traversal mode 2 enhanced for
        for(Object obj: set) {
            System.out.print(obj + " ");// Gork smiles
        }

Common methods:

Like the List interface, the Set interface is also a sub interface of the Collection interface. Therefore, common methods are the same as the Collection interface. The following is a simple example

apiexplain
addAdd a single element
removeDeletes the specified element
containsFind whether the element exists
sizeGet the number of elements
isEmptyJudge whether it is empty
clearempty
addAllAdd multiple elements
containsAllFind whether multiple elements exist
removeAllDelete multiple elements

Code demonstration:

        Set c = new HashSet();

        //1.add: add a single element
        c.add("Gork");
        c.add("half-and-half");
        c.add(999);
        c.add(true);
        System.out.println(c);// [Gork, fifty five, 999, true]

        //2.remove: deletes the specified element
        c.remove(999);
        System.out.println(c);// [Gork, 50 / 50, true]

        //3.contains: find whether the element exists
        System.out.println(c.contains("Gork")); //true

        //4.size: get the number of elements
        System.out.println("c of size=" + c.size());//3

        //5.isEmpty: judge whether it is empty
        System.out.println(c.isEmpty());//false

        //6.clear: clear deletes all elements of the current set
        c.clear();
        System.out.println(c); //[]

        //7.addAll: add multiple elements. Note that all combined elements are taken out and added, and add as a whole
        Set c2 = new HashSet();
        c2.add("Lu Benwei");
        c2.add("The Shy");
        c2.add(888);
        c2.add(true);
        c.addAll(c2);
        System.out.println(c); //[Lu Benwei, The Shy, 888, true]

        //8.containsAll: find whether multiple elements exist
        Set c3 = new HashSet();
        c3.add(888);
        c3.add(true);
        System.out.println(c.containsAll(c3));//true

        //9.removeAll: delete multiple elements. Note that if there are multiple same values in c, they will be deleted together
        c.removeAll(c3);
        System.out.println(c);//[Lu Benwei, The Shy]

2.2.1 HashSet

sketch:

  1. HashSet implements the Set interface
  2. HashSet is actually a HashMap. Take a look at the source code
    public HashSet() {
        map = new HashMap<>();
    }
  1. You can store null values, but there can only be one null value
  2. HashSet does not guarantee that the elements are ordered. It depends on the result of the index after hash. (that is, it is not guaranteed that the order in which the elements are stored is consistent with the order in which they are taken out)
  3. Cannot have duplicate elements

HashSet underlying mechanism Description:

  1. The bottom layer of HashSet is HashMap.
  2. When adding an element, first get the hash value - > will be converted to - > index value.
  3. Find the storage data table table and see if there are elements stored in the index position.
  4. If not, join directly.
  5. If yes, call the equals method for comparison. If it is the same, discard the addition. If it is different, add it to the end.
  6. In Java 8, if the number of elements in a linked list reaches TREEIFY_THRESHOLD (8 by default), and the size of the table > = 2) min_ TREEIFY_ Capability (64 by default), it will be trealized (red black tree).

2.2.2 LinkedHashSet

sketch:

  1. LinkedHashSet is a subclass of HashSet
  2. LinkedHashSet determines the storage location of elements according to the hashCode value of elements, but it also uses a linked list to maintain the order of elements (Figure), which makes elements appear to be saved in insertion order.
  3. The performance of LinkedHashSet is slightly lower than that of HashSet, but it has good performance when iteratively accessing all elements in the Set. (because the bottom layer maintains a hash table + two-way linked list)
  4. LinkedHashSet does not allow duplicate collection elements
  5. At the bottom of the LinkedHashSet is a LinkedHashMap, and the maintained linked list is a two-way linked list (figure below)

Differences among HashSet, TreeSet and LinkedHashSet

TreeSet pony hasn't been sorted out here and hasn't been used in development, but I understand everything in the interview. I borrow a very detailed picture summarized by brother ThinkWon


Summary:

  • HashSet is a Set with general functions
  • LinkedHashSet provides element insertion order guarantee
  • TreeSet is a SortedSet implementation. Elements are stored in the order specified by Comparator or Comparable.

3. Two column set (Map)

sketch:

  1. Map and Collection exist side by side. Used to save data with mapping relationship: key value
  2. The key and value in the Map can be data of any reference type
  3. The key s in the Map are stored by Set, and repeated [hashcode+equals] is not allowed
  4. The value in the Map can be repeated. Is stored using Collection
  5. The key and value of Map can be null
  6. String class is often used as the "key" of Map
  7. There is a one-way one-to-one relationship between key and value, that is, a unique and definite value can always be found through the specified key
  8. Map elements are unordered because key s are stored in sets. Set itself is disordered
  9. Map stores the key value diagram of data, and a pair of k-v is called Entry


Common methods of Map interface

apiexplain
putadd to
removeDelete mapping relationship based on key
getGet value according to key
sizeGet the number of elements
isEmptyJudge whether the number is 0
cleareliminate
containsKeyFind if key exists

Code demonstration:

        Map map = new HashMap();

        //1. put: add
        map.put("half-and-half", "Lu Benwei");
        map.put("Gork", "pony");
        map.put("smile", "Gao Xuecheng");
        map.put("The Shy", "Road ceiling");
        map.put("Faker", "Great demon king");
        System.out.println(map);//{fifty five = Lu Benwei, Gork = pony, Faker = great devil, The Shy = on the road ceiling, smile = Gao Xuecheng}

        //2.remove: delete the mapping relationship according to the key
        //Note: if the remove key does not exist, no error will be reported
        map.remove("Faker");
        System.out.println(map);//{fifty five = Lu Benwei, Gork = pony, The Shy = on the road ceiling, smile = Gao Xuecheng}

        //3.get: get value according to key
        System.out.println(map.get("half-and-half"));//Lu Benwei

        //4.size: get the number of key values
        System.out.println(map.size());//4

        //5.isEmpty: judge whether the number is 0
        System.out.println(map.isEmpty());//false

        //7.containsKey: judge whether the search key exists
        System.out.println(map.containsKey("The Shy"));//true
        System.out.println(map.containsKey("Faker"));//false

        //6.clear: clear
        map.clear();
        System.out.println(map);//{}

3.1 HashMap

sketch:

  1. HashMap is the most frequently used implementation class of Map interface.
  2. HashMap stores data in key Val pairs
  3. The key cannot be repeated, but the value can be repeated. Null keys and null values are allowed.
  4. If the same key is added, the original key val will be overwritten, which is equivalent to modification (key will not be replaced, val will be replaced)
  5. Like HashSet, the mapping order is not guaranteed, because the underlying is stored in the form of hash table
  6. HashMap does not achieve synchronization, so it is thread unsafe

HashMap underlying mechanism description
At jdk1 6,JDK1. In 7, HashMap is implemented by bit bucket (array) + linked list, that is, the linked list is used to deal with conflicts, and the linked lists with the same hash value are stored in a linked list. However, when there are many elements in a bucket, that is, there are many elements with equal hash values, the efficiency of searching by key value in turn is low. And jdk1 In 8, HashMap is implemented by bit bucket + linked list + red black tree. When the length of the linked list exceeds the threshold (8), the linked list is converted into red black tree, which greatly reduces the search time.

  • What are the differences between the jdk7 and 8 versions of HashMap?

    • Different data structures:
      The HashMap in 1.7 is an array + linked list structure
      The HashMap in 1.8 is an array + linked list + red black tree structure

    • The linked list is inserted in different ways:
      1.7 the head insertion method is used. The thread safety problem of the head insertion method during capacity expansion leads to the dead cycle of the linked list
      1.8 tail interpolation is used

    • The index is recalculated in different ways after capacity expansion:
      1.7 the expanded size will be used to recalculate the index with the hash
      1.8 will judge whether the previous hash needs to add the calculated index position is 0 or 1. If it is 0, it will remain in place. If 1 adds the new capacity to the current index, it will be the calculated index

  • How HashMap works
    HashMap is mainly used to store key value pairs. It is composed of array, linked list and red black tree. It will Hash the key value to obtain the corresponding index to access the nodes in the array. If there is a Hash conflict, a linked list will be formed, and the new elements will be placed last. When the length of the linked list is greater than 8 and the capacity of the array is greater than 64, a red black tree will be formed according to the current linked list. When the node in the red black tree is less than 6, it will be converted back to the linked list.

3.2 Hashtable

sketch:

  1. This class implements hashtable
  2. Element is a key value pair
  3. Neither key nor value of hashtable can be null
  4. hashTable is basically the same as hashMap
  5. But hashTable is thread safe and hashMap is thread unsafe

3.3 TreeMap

sketch:

  1. Duplicate key s are not allowed
  2. Can insert null key, null value
  3. You can sort elements
  4. Unordered collection (inconsistent insertion and traversal order)

Hashtable and TreeMap are not widely used in the development of small horses, so where they are not written in place, you can put forward different opinions in the comment area!

3.4 differences among HashMap, HashTable and TreeMap

4. How to select collection implementation classes in development

5. Collections tool class

sketch:

  1. Collections is a tool class that operates on collections such as Set, List, and Map
  2. Collections provides a series of static methods to sort, query and modify collection elements. It also provides methods to set immutable collection objects and realize synchronous control over collection objects

Common methods:

apiexplain
reverse(List)Reverse the order of elements in the List
shuffle(List)Random sorting of List collection elements
sort(List)Sorts the specified List collection elements in ascending order according to the natural order of the elements
sort(List,Comparator)Sorts the List collection elements according to the order generated by the specified Comparator
swap(List,int i, int j)Exchange the elements at i and j in the specified list collection
Object max(Collection)Returns the largest element in a given set according to the natural order of the elements
Object max(Collection,Comparator)Returns the largest element in a given collection in the order specified by the Comparator
Object min(Collection)Returns the smallest element in a given set according to the natural order of the elements
Object min(Collection,Comparator)Returns the smallest element in a given collection in the order specified by the Comparator
int frequency(Collection,Object)Returns the number of occurrences of the specified element in the specified collection
void copy(List dest,List src)Copy the contents of src to dest
boolean replaceAll(List list,Object oldVal,Object newVal)Replace all old values of the List object with the new values

Code demonstration:

        List list = new ArrayList();
        list.add("Gork");
        list.add("half-and-half");
        list.add("The Shy");
        list.add("pony");
        list.add("pony");
        list.add("Xiaolu");
        list.add("smile");
        list.add("LOL");
        System.out.println("list=" + list);//list=[Gork, The Shy, pony, pony, Lu, smile, LOL]

        //1.reverse(List): reverse the order of elements in the List
        Collections.reverse(list);
        System.out.println("After reversal list: " + list);//list after reversal: [LOL, smile, Lu, pony, pony, The Shy, fifty-five, Gork]

        //2.shuffle(List): randomly sort the elements of the List set

        Collections.shuffle(list);
        System.out.println("Random sorting list: " + list);//Random sort list: [pony, LOL, Lu, smile, pony, The Shy, Gork, fifty fifty]

        //3.sort(List): sort the elements of the specified List set in ascending order according to the natural order of the elements
        Collections.sort(list);
        System.out.println("Natural sorting:" + list);//Natural order: [Gork, LOL, The Shy, fifty five, Xiao Lu, Xiao Ma, Xiao Ma, smile]

        //4.sort(List,Comparator): sort the List set elements according to the order generated by the specified Comparator
        //Requirements, according to the length from large to small
        Collections.sort(list, new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                return ((String)o2).length() - ((String)o1).length();
            }
        });
        System.out.println("After sorting list: " + list);//list after sorting: [The Shy, Gork, LOL, fifty five, Xiao Lu, Xiao Ma, Xiao Ma, smile]

        //5.swap(List,int i,int j): exchange the elements at I and j in the specified list set
        Collections.swap(list, 0, 2);
        System.out.println("After exchange:" + list);//After the exchange: [LOL, Gork, The Shy, fifty five, Xiao Lu, Xiao Ma, Xiao Ma, smile]


        //6.Object max(Collection): returns the largest element in a given set according to the natural order of elements
        System.out.println(Collections.max(list));//smile

        //7. Object max(Collection, Comparator): returns the largest element in a given collection according to the order specified by the Comparator
        System.out.println(Collections.max(list,new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                return ((String)o1).length() - ((String)o2).length();
            }
        }));//The Shy

        //8.Object min(Collection)
        System.out.println(Collections.min(list));//Gork

        //9.Object min(Collection,Comparator)
        System.out.println(Collections.min(list, new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                return ((String)o1).length() - ((String)o2).length();
            }
        }));//Xiaolu

        //10. int frequency(Collection, Object): returns the number of occurrences of the specified element in the specified collection
        System.out.println(Collections.frequency(list, "pony"));//2

        //11. void copy(List dest,List src)
        List dest = new ArrayList();
        for (int i = 0; i < list.size(); i++) {
            dest.add(i);
        }
        Collections.copy(dest , list);
        System.out.println(dest);//[LOL, Gork, The Shy, fifty fifty, Xiao Lu, Xiao Ma, Xiao Ma, smile]

        //12. Boolean replaceall (List, Object oldVal, Object newVal): replace all old values of the List object with new values
        Collections.replaceAll(list, "LOL", "League of Heroes");
        System.out.println("After replacement list: " + list);//list after replacement: [League of heroes, Gork, The Shy, 50-50, Xiao Lu, Xiao Ma, Xiao Ma, smile]

Daily summary

  • Pony thinks that ArrayList and HashMap must be familiar with their use. They are still used in most of the development
  • Small partners with capacity expansion mechanism must know about it. They may be asked in the interview
  • Collections tool class can be knocked by hand, which will make our development efficiency get twice the result with half the effort

The above is what pony wants to send today. This article has been sorted out for a long time. Welcome to learn from each other and make progress together. You can also interact in the comment area! 👇

Keywords: Java Back-end

Added by Krik on Fri, 10 Dec 2021 02:05:23 +0200