java collection study notes Collection

Insert picture description here
Insert picture description here

The collection of learning records in java
should rewrite the toString method.
Array: Once the length of the array in java is determined, it cannot be changed, and the data whose quantity will change cannot be stored.
(2) Store the same type of data

Collection: It can save an indeterminate amount of data. What's more attractive is that a collection can save data with a mapping relationship, and only objects
(reference variables of objects) can be saved in the collection . No need to define the length, the collection will dynamically increase or decrease the length.
Collection class, mainly derived from two interfaces Collection and Map
java.util.Collection, java.util.Map

Collections: This class only contains static methods that operate on collections or return collections. It contains a polymorphic algorithm that operates on a collection, a "wrapper" (wrapper), which returns a new collection supported by the specified collection, as well as some other odds and ends.
One, Colloction interface

(1) Set interface features: elements are disordered, and elements cannot be repeated (there is no method that accepts a comparator as a parameter)
//It is best to rewrite the toString method for a class written by yourself.
// If you want to use the Set collection, then Also need to rewrite equals() method and hashcode() method? ? ? (There are still errors, I don’t understand very well)
1. HashSet class (if you judge whether the object is the same object according to the attribute to complete the instance, you need to rewrite the equals method and hashcode
method in the class
(1) the added elements are out of order
(2) HashSet It is not synchronized. If multiple threads access a HashSet at the same time, for example, when modifying, it must be synchronized manually to ensure thread safety.
(3) The element value can be null
(4) When adding an element to the HashSet collection By default, the hashCode() method is called to obtain the hashcode value of the object, which is used to determine the location of the object in the HashSet.
(5) If two elements are compared, the equals() method returns true, but the value returned by hashCode() is not Same, it means that the two elements are different
(6) Therefore, the HashSet set judges whether the two elements are equal, that is, through the equals() method to compare, and the hashCode value is also compared together.

2. The LinkedHashSet class, which determines the storage location of the element according to the hashCode value of the element, but also uses a linked list to maintain the order of the elements.
When accessing it, the elements in the collection will be accessed according to the order in which the elements are added. There is an advantage that the performance during access will be very good.
However, because of the chain structure, the performance is slightly worse than HashSet when inserting data, and it is not recommended to use it when inserting elements.

Compared with HashSet, insertion is slow and access is fast

3... TreeSet class (compare the Comparable interface and override the abstract method. It sorts the data by default integer ascending order. See pet3 when custom sorting is needed)
(1) The underlying storage is related to red-black trees and binary trees.
(2) Sorting can be performed, because TreeSet is an implementation class of the SortedSet interface.
(3) TreeSet can ensure that the elements are in a sorted state, so TreeSet uses a data structure of red and black numbers to store set elements.
(4) The sorting rules are: natural sorting and custom sorting (natural sorting is the default ascending order).
Anonymous internal The class implements or directly implements the Comparable interface for the entire class

import java.util.Comparator;
import java.util.TreeSet;
public class Pet3 {
    
    
    int age;
    public Pet3(int age) {
    
    
        this.age = age;
    }
    @Override
    public String toString() {
    
    
        return "Pet2{" +
                "age=" + age +
                '}';
    }
    public static void main(String[] args) {
    
    
        TreeSet<Pet3> treeSet = new TreeSet<Pet3>(new Comparator<Pet3>() {
    
    
            //匿名内部类
            @Override
            public int compare(Pet3 o1, Pet3 o2) {
    
    
                //现在是降序
                return o1.age-o2.age;
            }
        });
        treeSet.add(new Pet3(18));
        treeSet.add(new Pet3(87));
        treeSet.add(new Pet3(3));
        treeSet.add(new Pet3(3));
        System.out.println(treeSet);
    }
}

```java
import java.util.Comparator;

public class Pet implements Comparable<Pet> {
    
    
    String name;
    String color;
    int age;
    public Pet(String name, String color, int age) {
    
    
        this.name = name;
        this.color = color;
        this.age = age;
    }
    @Override
    public String toString() {
    
    
        return "Pet{" +
                "name='" + name + '\'' +
                ", color='" + color + '\'' +
                ", age=" + age +
                '}';
    }
    @Override
    public int compareTo(Pet o) {
    
    
        return this.age-o.age;
    }
    /**
    @Override
    public int compareTo(Pet2 o) {
        //现在是降序
        if (this.age > o.age) return -1;
        if (this.age < o.age) return +1;
        return 0;
    }
    */
}

(5) TreeSet will call the compareTO(Object obj) method to compare the size relationship between the elements, and sort them in ascending order.
(6) The Comparable interface mainly provides standards for comparing sizes. Some common classes that will be encountered in the future:
BigDecimal, BigInteger
(6) When TreeSet adds elements, the compareTO method will be called to compare the size and find the position according to the red-black tree. If the table corners are equal through the compareTo() method,
it cannot be added.

4. The
EnumSet class does not have a constructor. (1) The elements in the EnumSet class must be enumeration values ​​of the specified enumeration type. EnumSet determines the specific order of the set elements in the order of enumeration value definition
(2) EnumSet mainly uses It is stored in the form of a bit vector, which is very compact, efficient, small in memory, and very efficient in operation, so the execution speed is very fast, especially suitable for batch
operations
(3) EnumSet cannot add null, otherwise it will report a null pointer exception
(4) Enumet needs to use class methods to create object instances
(5) The specified enumeration value is stored in the enumeration collection.

import java.util.EnumSet;
enum Day {
    
    
    ONE,TWO,THREE,FOUR,FIVE
}
public class EnumSetDemo {
    
    
    public static void main(String[] args) {
    
    
        EnumSet<Day> allof = EnumSet.allOf(Day.class);
        System.out.println(allof);

        EnumSet es2 = EnumSet.noneOf(Day.class);
        System.out.println(es2);

        es2.add(Day.THREE);

        System.out.println(es2);

        //以指定的枚举值创建EnumSet集合
        EnumSet<Day> es3 = EnumSet.of(Day.ONE,Day.THREE);
        System.out.println(es3);

        EnumSet<Day> es4 = EnumSet.range(Day.ONE,Day.THREE);
        System.out.println(es4);

        //es5的集合元素+es4集合元素 = Day枚举类型的全部枚举值
        //排除es4中已有的数据
        EnumSet<Day> es5 = EnumSet.complementOf(es4);
        System.out.println(es5);
    }
}

(2) Queue interface
1. PriorityQueue PriorityBlockingQueue (Priority Queue)
PriorityQueue is not thread-safe, so Java provides PriorityBlockingQueue (implementing BlockingQueue interface) for Java multithreading environment.

2. Deque interface and ArrayDeque implementation class
(1) ArrayDeque is a specific implementation of the Deque interface, which depends on the variable array to achieve. ArrayDeque has no capacity limitation and can be
automatically expanded according to demand . ArrayDeque does not support elements whose value is null.
The LinkedList class implements the Deque interface and the List interface

(3) List interface characteristics: the stored elements can be stored repeatedly. The elements are ordered
//Iterator and ListIterator interface usage and the difference between the two
: 1...Iterator interface is more general, including both Set and Map. , ListIterator can only be used for List
2.Iterator is one-way,
usage

public class ListDemo {
    
    
    public static void main(String[] args) {
    
    
        List l1 = new ArrayList();
        l1.add("ddd");
        l1.add(1);
        l1.add(1);
        l1.add(1);
        l1.add(1,"张三");
        System.out.println(l1);
        l1.set(2,"还");
        //遍历 for循环 foreach迭代器
        System.out.println(l1.indexOf("张三"));
        System.out.println("***************");
        for (int i = 0;i < l1.size();i++){
    
    
            System.out.println(l1.get(i));
        }
        System.out.println("***************");
        for (Object o1:l1){
    
    
            System.out.println(o1);
        }
        //迭代器
        Iterator iterator = l1.iterator();
        while (iterator.hasNext())
        {
    
    
            System.out.println(iterator.next());
        }
        System.out.println("***************");
        //列表迭代器
        //正序
        ListIterator listIterator = l1.listIterator();
        while (listIterator.hasNext())
        {
    
    
            System.out.println(listIterator.next());
        }
        //倒序----------------------------------------------------
        ListIterator li2 = l1.listIterator();
        while (li2.hasPrevious())
        {
    
    
            System.out.println(li2.previous());
        }
    }
}在这里插入代码片

public Iterator iterator() {return ListIterator();} //This is the iterator method implemented in the ArraysList class
//The difference between
Comparator and Comparable The difference between Comparator and Comparable is reproduced in two of the 82-year-old Qingfeng
Collections class Method
public static <T extends Comparable<? super T>> void sort(List list) { list.sort(null); } //Any class that implements the Comparable interface can use this method

public static void sort(List list, Comparator<? super T> c) { list.sort©; }//Need to pass in a comparator

//Commonly used method
add(int index, E element) to the specified position
add(E e) adds the specified element to the end of this list
addAll​(int index, Collection<? extends E> c) will specify all in the collection Insert the element into the specified position in this list (optional operation).
addAll​(Collection<? extends E> c) Appends all elements in the specified collection to the end of this list in the order returned by the iterator of the specified collection (optional operation).
clear() Remove all elements from this list (optional operation).
contains​(Object o) returns true whether this list contains the specified element
containsAll​(Collection<?> c) ​​returns true whether this list contains all elements of the specified collection​​.
get​(int index) Returns the element at the specified position in this list
//Related commonly used implementation classes
1. ArrayList The underlying array collection is fast to traverse, and the speed of accessing elements is fast and asynchronous (thread insecurity): if multiple threads access & modify ArrayList collection,
you need to manually ensure the synchronization of the collection.
2. Vector features: ordered and repeatable because the array collection is fast to traverse, and random access to elements is also fast to insert and delete.
3. ArrayList and Vector implementation classes
They are all List classes based on arrays. Encapsulates a dynamic Object[] array that allows redistribution. It is mainly used for the initialCapacity parameter to set the length of the array.
When too many elements are added, the initialCapacity will automatically grow, the default length is 10.

Sometimes you need to pay attention to performance issues. If you add a large number of elements to these two collections, you can use the ensureCapacity(minCapacity) method to increase the initialCapacity at one time.
This can reduce the number of allocations and improve performance.

They can also use the ensureCapacity(minCapacity) and trimToSize() methods to reallocate the Object[] array

Vector is a relatively old collection. It is the predecessor of ArrayList. It has many shortcomings and is not recommended.

ArrayList is not thread-safe. If multiple threads access & modify the ArrayList collection, you need to manually ensure the synchronization of the collection

Vector is thread-safe, so the performance will be slightly lower than ArrayList, even if it is thread-safe, it is not recommended. Later, we can use the
Collections utility class to talk about ArrayList becoming thread-safe.

4.
The asList (Object… a) method of the List Arrays class with the same length can convert an array or a specified number of objects into a List collection, which is neither an ArrayList.
An instance of the implementation class is not an instance of the Vector implementation class, but an instance of the internal class ArrayList of Arrays. (You can view
the source code of the Arrays class ).
Arrays.ArraysList is a fixed-length List collection, which can only access elements, and cannot add or delete elements in the collection.

5.LinkedList

Guess you like

Origin blog.csdn.net/weixin_45773632/article/details/109441146
Recommended