List and Set study notes in Java collections

Overview

As shown in the figure:
Insert picture description here

List interface

    Duplicate elements are allowed in the List collection. All elements are stored in a linear manner, and the specified element can be found by index. The characteristic is that the stored elements are orderly and repeatable.

ArrayList collection

    ArrayList is the implementation class of the List interface. ArrayList encapsulates a variable-length array object. If the stored elements exceed the length of the array, ArrayList will allocate a larger array in memory to store these elements.
Common methods:
Insert picture description here
Examples:

public class Exception01 {
    
    
    public static void main(String[] args) {
    
    
        //创建ArrayList集合
        ArrayList<String> arrayList = new ArrayList<String>();
        arrayList.add("张三");
        arrayList.add("李四");
        arrayList.add("王二");
        arrayList.add("麻子");
        System.out.println("数组长度为:" + arrayList.size());
        System.out.println("数组最后一个元素是:" + arrayList.get(arrayList.size()-1));
        //遍历集合中的元素
        for(String list : arrayList){
    
    
            System.out.println(list);
        }
    }
}

    The starting index of the first element of ArrayList starts from 0, and the last element is size-1. When accessing an element, it must be noted that the element index cannot exceed the range of size-1. Otherwise, IndexOutOfBoundsException will be thrown. It is precisely because the bottom layer of ArrayList encapsulates a variable array, when adding or deleting elements at a specified position, it causes the creation of a new array, which is relatively inefficient, so it is not suitable for a large number of additions and deletions. But it is suitable to find the element through search faster.

LinkeList collection

    The internal encapsulation of the LinkeList collection is a doubly linked list. Each element in the linked list uses a reference to remember its previous and next elements, thus connecting all the elements. When we insert an element, we only need to change the index relationship before and after the element, and the same is true for deletion. It is this characteristic that the LinkeList collection has a very high efficiency for the addition and deletion of elements.
Common methods: Insert picture description here
Examples:

public class Exception02 {
    
    
    public static void main(String[] args) {
    
    
        LinkedList<Object> linkedList= new LinkedList<Object>();
        linkedList.add("A");
        linkedList.add("B");
        linkedList.add("C");
        linkedList.add("D");
        //循环遍历输出
        for (Object list: linkedList){
    
    
            System.out.println(list);
        }
        System.out.println("元素长度为:" + linkedList.size());
        System.out.println("集合的第一个是:" + linkedList.getFirst());
        System.out.println("集合的最后一个是:" + linkedList.getLast());
        //在集合头部添加一个元素
        linkedList.addFirst("F");
        //在集合尾部添加一个元素
        linkedList.addLast("L");
        System.out.println("添加后集合的第一个是:" + linkedList.getFirst());
        System.out.println("添加后集合的最后一个是:" + linkedList.getLast());
        System.out.println("------------------------------------------");
        //移除集合头部添加一个元素
        linkedList.removeFirst();
        //移除集合尾部添加一个元素
        linkedList.removeLast();
        System.out.println("移除后集合的第一个是:" + linkedList.getFirst());
        System.out.println("移除后集合的最后一个是:" + linkedList.getLast());
        //移除指定位置的元素
        linkedList.remove(0);
        System.out.println("移除指定位置后集合的第一个是:" + linkedList.getFirst());
    }
}

Vector collection

    The Vector collection is also based on an array, which is very similar to the ArrayList, but it is thread-safe and inefficient, and it is not used much now.

Set interface

    The elements in the Set interface are disordered, and the stored elements do not repeat. The Set interface mainly has two implementation classes, HashSet and TreeSet. HashSet determines the storage location of the element in the set according to the hash value of the object, so it has good access and search performance. TreeSet is a binary tree to store elements, it can sort the elements in the set.

HashSet collection

    HashSet is an implementation class of the Set interface. The elements in it are not repeatable and the elements are unordered. When storing an element in the HashSet collection, first call the object's hashCode() method to determine the storage location of the element, and then call the object's equals() to ensure that there are no duplicate elements at that location.
Examples:

public class Exception03 {
    
    
    public static void main(String[] args) {
    
    
        HashSet hashSet = new HashSet();//创建hashset集合
        hashSet.add("A");//存入元素
        hashSet.add("B");
        hashSet.add("C");
        hashSet.add("A");
        Iterator iterator = hashSet.iterator();//获得iterator对象
        while (iterator.hasNext()){
    
    
            //如果有元素通过迭代器next()获得元素
            Object next = iterator.next();
            System.out.println(next);
        }
    }
}

Operation result: The
Insert picture description here
    reason why the HashSet collection cannot store the same element is because when we add elements through the add() method, we first call the hashCode() method of the current object to obtain the hash value of the object, and then calculate it based on the hash value Create a storage location. If there is no element above the position, store the element directly. If there is an element at the position, the equals() method will be called to compare the currently stored element with the element at the position in turn, and if it returns false, the element will be stored in the collection. If it returns true, indicating that there is a duplicate element, the element will be discarded.

TreeSet collection

    TreeSet is another implementation class of the Set interface. It internally uses a self-balancing binary tree to store elements. This structure ensures that the elements stored in the set will not be repeated and can be sorted.
Examples:

public class Exception04 {
    
    
    public static void main(String[] args) {
    
    
        //创建TreeSet集合
        TreeSet treeSet = new TreeSet();
        treeSet.add(6);//添加四个元素
        treeSet.add(9);
        treeSet.add(5);
        treeSet.add(7);
        //通过迭代器遍历集合中的元素
        Iterator iterator = treeSet.iterator();
        while (iterator.hasNext()){
    
    
            System.out.println(iterator.next());
        }
    }
}

Running result: The
Insert picture description here
    result shows that the elements stored in the TreeSet collection are deduplicated and output in sorted order. The reason why sorting is possible is because when an element is stored in the TreeSet collection, the element is compared with other elements, and they are finally inserted into an ordered sequence of objects. The compareTo() method is called when comparing the elements of the collection. This method is defined in the Comparable interface. Therefore, if you want to sort the elements in the collection, you must implement the Comparable interface. Most of the classes in the JDK implement the Comparable interface, so they automatically have a compareTo() method. If the custom class wants to sort, it must implement the Comparable interface .

Guess you like

Origin blog.csdn.net/qq_42494654/article/details/109540569