Detailed Explanation of Collections Class

Table of contents

1. Collections overview:

   1.1 What is the Collections class:

   1.2 The difference and connection between Collections class and collection:

2. The main method of the Collections class:

1. Collections overview:

     1.1 What is the Collections class:

  • Java.util.Collections is a collection tool class for operating collections such as LIst, Set, and Map.

  • The Collections class provides a series of static methods that can implement operations such as sorting collection elements, adding some elements, random sorting, and replacement.

       Note: The Collections class cannot be new, not because there is no constructor, but because the constructor of Collections is privatized. But the calling method can directly call the method of the Collections class through the class name, because the methods in the Collections class are all modified by static, and can be called directly with the class name.

   1.2 The difference and connection between Collections class and collection:

the difference:

  • Collections is a tool class with properties and static methods
  • Collection is a root interface, below which there are List and Set interfaces, and each of the two interfaces has their specific implementation classes.
  • They only differ by one letter, but the two are completely different concepts.

connect:

  • Collections provides many methods for the Set and List collections under the collection interface to facilitate better processing of the elements in the collection.

2. The main method of the Collections class:

The methods in Collections are all static methods, which can be called directly by class name. method name.

1. public static void shuffle(List). chaos sort   

2. public static <T> boolean addAll(Collection<T> c, T... elements). add some elements

3. public static <T> void sort(List<T> list, Comparator<? super T>). Sort, sort the elements in the collection according to the specified rules

4. public static <T extends Comparable<? super T>> void sort(List<T> list). Sort, sort the elements in the collection according to the default rules.

5. public static int binarySearch(List list, Object key). Search, use the binary search method to search the specified List collection to obtain the index of the specified object in the List collection. If you want this method to work properly, you must ensure that the elements in the List are already in an ordered state.

6. public static void copy(List <? super T> dest, List<? extends T> src) copy, used to copy all elements in the specified collection to another collection.

7. public static void replaceAll(). Replace, replace all old elements in the collection with new elements

1.shuffle() random sorting:

The shuffle method is used to randomly shuffle the elements in the collection from their original order.

          Note: The collection in shuffle can only be a List collection. The Set collection will report an error.

Use Cases:

import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;

public class CollectionsTest {
    public static void main(String[] args) {

//创建一个Linkedlist集合
     LinkedList linkedList = new LinkedList();
        inkedList.add(123);
        linkedList.add(456);
        linkedList.add(234);
        linkedList.add(567);
 for (int i = 0; i <linkedList.size() ; i++) {
            System.out.println(linkedList.get(i));
        }

        //打乱顺序
        Collections.shuffle(linkedList);
        System.out.println("===========");
        System.out.println("打乱顺序之后:");
  for (int i = 0; i <linkedList.size() ; i++) {
            System.out.println(linkedList.get(i));
        }
    }

}

operation result:

2. addAll() adds some elements:

effect:

The addAll method is used to quickly add some elements to the collection

usage:

The first formal parameter puts the collection object, and then puts parameter 1, parameter 2, variable parameter type... .

What is a variable parameter type?

When a parameter in a method is actually called, the number of actual parameters can be 0, or 1, or more. This parameter is a variable parameter. The meaning of the variable parameter parameter: it is convenient to call the method, and any number of data of the same type can be passed in.

important point:

  1. If there are multiple parameters in the method, the variable parameters should be placed last.

  2. A method can have only one variable parameter

Use Cases:

1. Create multiple student objects.

2. Use the addAll method to load the students into the Linkedlist collection

import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;

public class CollectionsTest {
    public static void main(String[] args) {
//创建一个linkedlist集合
        LinkedList linkedList = new LinkedList();
        Student student1 = new Student(1, "章1");
        Student student2 = new Student(6, "章2");
        Student student3 = new Student(9, "章3");
        Student student4 = new Student(1, "章4");
Collections.addAll(linkedList,student1,student2,student3,student4);
for (int i = 0; i <linkedList.size() ; i++) {
            System.out.println(linkedList.get(i));
        }

operation result:

3. sort() natural sorting:

effect:

Sort the elements in the set in ascending or descending order according to the rules, or do nothing.

important point:

When using the sort method, the collection elements must be a subtype of Comparable, that is, the elements in the collection must implement the comparaTo method in the comparable interface. Otherwise this method cannot be used.

public int compareTo(T o);

This abstract method must be implemented in order to use the sort method. But since some of our basic commonly used classes such as String, wrapper classes of basic data types, etc. have already implemented this method, so we don't need to rewrite this method ourselves. To use the sort method of a custom type, the comparaTo method must be implemented.

4.sort() custom sorting:

A custom type, such as a student class, has attributes: age, name, etc. Create multiple student class objects and put them into the List collection. When customizing the sort method, the comparaTo method must be rewritten.

@Override
    public int compareTo(Student2 o) {
        return this.age-o.age;
    }

The comparaTo method after rewriting. 

sort() after overloading:

The sort() method also has a second type (collection, new Comparator<Object>)

Comparator is an interface, which is actually a new implementation class of Comparator, but the abstract method inside must be implemented.

Use Cases:

1. Customize a student class with age, name, and grade attributes.

2. Create 5 student objects, and then output them in ascending order of age and descending order of grades according to their age.

import java.util.Collections;
import java.util.LinkedList;

public class CollectionsTest2 {
    public static void main(String[] args) {
        LinkedList linkedList = new LinkedList();
        Student2 student1 = new Student2(10, "章1");
        Student2 student2 = new Student2(16, "章2");
        Student2 student3 = new Student2(19, "章3");
        Student2 student4 = new Student2(18, "章4");
        //把对象添加到集合中
        Collections.addAll(linkedList,student1,student2,student3,student4);
        Collections.sort(linkedList);
        for (int i = 0; i <linkedList.size() ; i++) {
            System.out.println(linkedList.get(i));
        }
    }
}
class Student2 implements Comparable<Student2>{
    int age;
    String name;
    public Student2(int age, String name) {
        this.age = age;
        this.name = name;
    }

    @Override
    public String toString() {
        return "Student2{" +
                "age=" + age +
                ", name='" + name + '\'' +
                '}';
    }
    @Override
    public int compareTo(Student2 o) {
        return this.age-o.age;
    }
}

 

important point:

1. Sorting according to a certain rule is what attribute is used to compare when rewriting the comparaTo method. The attribute of this comparison is the comparison rule sorting.

2. Implement ascending or descending order rules: this (the object of the current calling method) o (the parameter is passed in)
        all the logic at the bottom of the comparison is a pairwise comparison logic, returning a positive
        number of the comparison result this.age > o.age
        negative number this .age < o.age
        0 this.age==o.age.

6.copy() copy:

 Function: Copy all elements in the specified collection to another collection.

 use:

(List <? super T> dest,List<? extends T> src)

dest is the target collection, and src is the original collection. Put the elements in the original collection into the target collection.

Points to note:

1. The original collection is copied to the target collection, and the original collection will overwrite the elements in the target collection. This coverage starts from index value 0 until the original collection is copied.

2. The length of the target collection is at least the same as the length of the source collection. If the length of the target collection is longer, it does not affect the remaining elements in the target collection. If the target collection is not long enough to contain the entire source collection elements, the program will throw an IndexOutOfBoundsException exception.

3. The copy method can only copy the List collection, not the set collection

Personal opinion: I don't think it is very useful because it will overwrite the elements of the target collection

Use Cases:

1. Assign set 1 to set 2

import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;

public class CollectionsTest2 {
    public static void main(String[] args) {
        LinkedList linkedList = new LinkedList();
        LinkedList linkedList1 = new LinkedList();
//创建两个set集合
        HashSet hashSet = new HashSet();
        HashSet hashSet1 = new HashSet();

        linkedList1.add(123);
        linkedList1.add(222);
        linkedList.add(333);
        linkedList.add(444);
        linkedList.add(888);
        hashSet.add(234);
        hashSet1.add(666);
        Collections.copy(linkedList, linkedList1);
          //使用copy方法复制set会报错
//        Collections.copy(hashSet,hashSet1);
        for (int i = 0; i < linkedList.size(); i++) {
            System.out.println(linkedList.get(i));
//        }
        }
    }
}

operation result:

7. replaceAll(). replace:

Function: Replace all old elements in the collection with new elements

use:

(List list, Object oldVal, Object newVal)

list needs to be replaced, oldval needs to be replaced, newval new value

Use Cases:

Replace 333 in the set with the string "8888"

import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;

public class CollectionsTest2 {
    public static void main(String[] args) {
        LinkedList linkedList = new LinkedList();
        linkedList.add(123);
        linkedList.add(222);
        linkedList.add(333);
        linkedList.add(444);
        linkedList.add(888);
        hashSet.add(234);
        hashSet1.add(666);
//替换
        Collections.replaceAll(linkedList,333,"8888");
        for (int i = 0; i < linkedList.size(); i++) {
            System.out.println(linkedList.get(i));
//        }
        }
    }
}

Guess you like

Origin blog.csdn.net/qq_50692350/article/details/126292057