Java collection notes---To be continued

# 1. Collection interface and common methods

## 1. Methods of Collections interface

```java
        //add adds a single element G
        List list = new ArrayList();
        list.add("1");
        list.add(10);//list.add(new Integer(10))
        list.add (true);
        System.out.println("list="+list);
        //remove deletes the specified element
// list.remove(1);//removes the second element
        list.remove("1");/ /Delete the specified object
        System.out.println("list="+list);
        //contains: Find whether the element exists
        System.out.println(list.contains(10)); //true
        //size: Get the number of elements Number
        System.out.println(list.size());//2
        //isEmpty: Determine whether it is empty
        list.clear();
        //System.out.println("list="+list);
        //addAll :Add multiple elements
        ArrayList<Object> list1 = new ArrayList<>();
        list1.add("java");
        list1.add("python");
        list.addAll(list1);
        System.out.println("list="+list );
        //containsAll: Find whether multiple elements exist
        System.out.println(list.containsAll(list1));//true

        //removeAll: Delete multiple elements
        list.add("c++");
        list.removeAll(list1);
        System.out.println("list="+list);
```

## 2. How the Collection interface traverses elements

### 1. Use Iterator

​ 1. The Iterator object is called an iterator and is mainly used to traverse the elements in the Collection.

2. All collection classes that implement the Collection interface have an iterator() method, which is used to return an object that implements the iterator interface, that is, it can return an iterator.

3. The structure of iterator;

![image-20230204102423910](D:\study\Java_study\image\iterator.png)

4. Iterator is mostly used to traverse collections. Iterator itself does not store objects.

​ **Note: Iterator.hasNext() must be called for detection before calling the iterator.next() method, otherwise an exception will be thrown**

```java
package com.demo.collection;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

public class CollectionIterator {     public static void main(String[] args) {         Collection arrayList = new ArrayList();         arrayList.add(new Book("java","Programmer 1",1));         arrayList.add(new Book ("python","Programmer 2",2));         arrayList.add(new Book("c++","Programmer 3",3));




        System.out.println("arrayList"+arrayList);
        //1. First get the iterator corresponding to arraylist
        Iterator iterator=arrayList.iterator();
        System.out.println(iterator);
        while (iterator.hasNext()) {//Determine whether there is still data
            //Return the next element, the type is Object
            Object obj=iterator.next();
            System.out.println("obj"+obj);
        }
        //3. When the iterator exits while After the loop, the iterator points to the last element at this time, so the iterator needs to be recreated
        //It can also be said to obtain a new iterator
        iterator=arrayList.iterator();
        System.out.println(iterator);
        //while loop Quickly generate shortcut keys while ===>itit
        //Display all shortcut keys ctrl+j
    }
}
class Book{     private String bookName;

    public Book(String bookName, String name, int age) {
        this.bookName = bookName;
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getBookName() {
        return bookName;
    }

    public void setBookName(String bookName) {
        this.bookName = bookName;
    }

    private String name;
    private int age;

    @Override
    public String toString() {
        return "Book{" +
                "bookName='" + bookName + '\'' +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

```

### 2. Enhancement of for loop

Enhanced for loops can be used not only in collections, but also in arrays.

The bottom layer of enhanced for is also an iterator;

Enhanced for can be understood as a simplified version of iterator traversal;

# 2. List interface and common methods

## 1. Basic introduction to the list interface

The list interface is a sub-interface of the Collection interface;

```java
//The elements in the list collection class are in order (that is, the order of addition and the order of removal are consistent, and can be repeated
List list = new ArrayList();
list.add(1);
list.add(2);
list.add (3);
list.add(4);
System.out.println("list"+list);
//2. Each element in the list collection has its corresponding sequential index, that is, it supports index
// The index is
System.out.println(list.get(0)) starting from 0 ;
```

Commonly used ones include ArrayList, LinkedList and Vector

## 2. Common methods of List interface

```java
        List list = new ArrayList();
        list.add("Zhang Sanfeng");
        list.add("Jia Baoyu");
        //void add(int index,Object ele): Insert the ele element at the index position
        / /Insert an object at index = 1

        list.add(1,"Liu Bei");
        //boolean addAll(int index, Collection eles): Add all elements in eles starting from the index position
        List list1=new ArrayList<>();
        list1.add(" java");
        list.addAll(1,list1);
        list.add("Zhang Sanfeng");
        System.out.println("list"+list);
        //Object get(int index): Get the element at the specified index position
        //int indexOf(Object obj): Returns the position where obj first appears in the collection
        System.out.println(list.indexOf("java"));
        // int lastIndexOf(Object obj): Returns the last time obj appears in the current collection Appearance position
        System.out.println(list.lastIndexOf("Zhang Sanfeng"));
        //Object remove(int index): Remove the element at the specified index position and return this element
        System.out.println(list.remove( 4));
        //Object set(int index,Object ele): Set the element ele at the specified index position, which is equivalent to replacement.
        list.set(2,"python");//If the set index does not exist, an exception will be thrown
        System.out.println("list"+list);
        //List subList(int fromIndex,int toIndex): Return from Subset from fromIndex to toIndex position
        // Note that the returned subset fromIndex <= subList <
        //The return interval is a List that is closed at the front and open at the end
        list2=list.subList(0,2);
        System.out.println("List2" +list2);
```

### 3. Three traversal methods of list

```java
        System.out.println("============Iterator=========");
        Iterator iterator=list.iterator();
        while (iterator.hasNext ()) {             Object next = iterator.next();             System.out.println(next);         }         System.out.println("========Ordinary for loop======== ===");         for (int j = 0; j < list.size(); j++) {             System.out.println(list.get(j));         }         System.out.println("===== ===Enhanced for loop==========");         for (Object obj :list) {             System.out.println(obj);         } ```











# 3. ArrayLisr underlying structure and source code analysis

arryalist can add null, and can put multiple

```java
    //ArrayList is thread-unsafe, check the source code, there is no synchronized keyword modification
    /*
public boolean add(E e) {     ensureCapacityInternal(size + 1); // Increments modCount!!     elementData[size++] = e ;     return true; }      */     List list = new ArrayList();     list.add(null);     list.add("java");     list.add(null);     System.out.println(list); ```










## 1. Source code analysis of the underlying operating mechanism of ArrayList (important and difficult points)

### 1. ArrayList maintains an array elementData of type Object.

```java
transient Object[] elementData; //transient means instant, short-lived, indicating that the property will not be
serialized```

### 2. When creating an ArrayList object, if the no-parameter constructor is used, the initial elementData capacity is 0. When adding it for the first time, the elementData is expanded to 10. If it needs to be expanded again, the elementData is expanded by 1.5 times.

Created an empty elementData empty array

```java
public ArrayList() {
    this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
```

Execute list.add

1. First determine whether to expand the capacity

2. Then perform the assignment operation

```java
public boolean add(E e) {
    ensureCapacityInternal(size + 1);  // Increments modCount!!
    elementData[size++] = e;
    return true;
}
```

```java
private void ensureCapacityInternal(int minCapacity) {
    ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
    private static int calculateCapacity(Object[] elementData, int minCapacity) {
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            return Math.max(DEFAULT_CAPACITY, minCapacity);
        }
        return minCapacity;
    }
```

1.modcount++ records the number of times the current collection has been modified

2. If the size of elementData is not enough, call group to expand it.

```java
private void ensureExplicitCapacity(int minCapacity) {
    modCount++;

    // overflow-conscious code
    if (minCapacity - elementData.length > 0)
        grow(minCapacity);
}
```

1. Expansion method

2. Use the expansion mechanism to determine how large the capacity needs to be expanded.

3. First time newCapacity =10

4. The capacity will be expanded by 1.5 times for the second time and thereafter.

5. Capacity expansion uses Arrays.copyOf()

```java
private void grow(int minCapacity) {
    // overflow-conscious code
    int oldCapacity = elementData.length;
    int newCapacity = oldCapacity + (oldCapacity >> 1);
    if (newCapacity - minCapacity < 0)
        newCapacity = minCapacity;
    if (newCapacity - MAX_ARRAY_SIZE > 0)
        newCapacity = hugeCapacity(minCapacity);
    // minCapacity is usually close to size, so this is a win:
    elementData = Arrays.copyOf(elementData, newCapacity);
}
```

### 3. If the constructor of the specified size is used, the initial capacity of elementData is the specified size. If expansion is needed again, directly expand the capacity by 1.5 times of elementData.

Analyze the source code of creating and using ArrayList with parameterized constructor

Created an elementData array of specified size

this.elementData = new Object[initialCapacity];

```java
public ArrayList(int initialCapacity) {
    if (initialCapacity > 0) {
        this.elementData = new Object[initialCapacity];
    } else if (initialCapacity == 0) {
        this.elementData = EMPTY_ELEMENTDATA;
    } else {
        throw new IllegalArgumentException("Illegal Capacity: "+
                                           initialCapacity);
    }
}
```

The expansion mechanism of the parameterized constructor will expand the capacity by 1.5 times of elementData for the first time.

The other principles are the same as the constructor without specifying a size

## 2. Vector underlying structure and source code analysis

### 1. Definition of Vector tired

```java
public class Vector<E>
    extends AbstractList<E>
    implements List<E>, RandomAccess, Cloneable, java.io.Serializable
```

### 2. The bottom layer of Vector is also an object array, protected Object[] elementData;

### 3. Vector is thread-synchronous, that is, thread-safe, and the operation method of Vector is synchronized.

```java
public synchronized int capacity() {
    return elementData.length;
}
```

### 4. During development, when thread synchronization security is required, consider using Vector.

### 5. Source code analysis

```java
package com.demo.list;

import java.util.Vector;

public class Vector_ {     public static void main(String[] args) {         //No constructor         //1, constructor          //1.1new Vector() constructs the bottom layer without parameters          /*             public Vector() {                     this(10);                 }           */          //1.2Vector parameterized constructor                /*             public Vector(int initialCapacity) {         this(initialCapacity, 0);     }          */         Vector vector = new Vector();         for (int i = 0; i < 10; i++ ) {             vector.add(i);         }         vector.add(100);         //2.Vector.add(i)





















        //2.1 The following method is to add data to the Vector collection
    /*
        public synchronized boolean add(E e) {         modCount++;         ensureCapacityHelper(elementCount + 1);         elementData[elementCount++] = e;         return true;     }      */         //2.2 Determine whether Required expansion conditions: minCapacity - elementData.length >0     /*         private void ensureCapacityHelper(int minCapacity) {         // overflow-conscious code         if (minCapacity - elementData.length > 0)             grow(minCapacity);     }      */         //2.3 If needed If the array size is not enough, expand it. The expansion algorithm is int newCapacity = oldCapacity + ((capacityIncrement > 0)?















        //                                         capacityIncrement : oldCapacity);
    /*
        private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
                                         capacityIncrement : oldCapacity);
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        elementData = Arrays.copyOf(elementData, newCapacity);
    }
     */
    }
}
```

## 3. Comparison of Vector underlying structure and ArrayList

![Comparison between the bottom layer of Vector and ArrayList](D:\study\Java_study\image\Comparison between the bottom layer of Vector and ArrayList.png)

## 4. LinkedList underlying structure

### 1. The bottom layer of LinkedList implements the characteristics of doubly linked lists and double-ended queues.

### 2. You can add any element (the element can be repeated), including null

### 3. The thread is not safe and synchronization is not implemented.

### 4. The underlying operating mechanism of LinkedList

1. A doubly linked list is maintained at the bottom of LinkedList.

2. 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, ultimately realizing a two-way linked list.

​ 4. Therefore, adding and deleting elements of LinkedList is not done through arrays, which is relatively more efficient.

5. Simulate a simple doubly linked list LinkedList01.java

```java
package com.demo.list;

public class LinkedList01 {     public static void main(String[] args) {         //Simulate a simple doubly linked list         Node jack = new Node("jack");         Node tom = new Node("tom");         Node java = new Node( "java");




        //Connect three nodes to form a doubly linked list
        //jack -> tom -> java
        jack.next=tom;
        tom.next=java;
        //java -> tom -> jack
        java.pre=tom;
        tom.pre= jack;

        Node first = jack; //Let the first reference point to jack, which is the head node of the two-way list.
        Node last = java; //Let the last reference point to java, which is the tail node of the two-way list.


        //演示:遍历
        System.out.println("first遍历");
        while (true){
            if (first==null){
                break;
            }else {
                System.out.println(first);
                first=first.next;
            }
        }
        System.out.println("last遍历");
        while (true){
            if (last==null){
                break;
            }else {
                System.out.println(last);
                last=last.pre;
            }
        }

        //Demonstration: Add objects/data to linked list
        //Requirement: Add an object Python between Tom and java
        //1. First create a Node node, the name is Python
        Node python = new Node("Python");
        python.next =java;
        python.pre=tom;
        tom.next=python;
        java.pre=python;
        //Let first point to jack again
        first=jack;
        //Let last point to java again
        last=java;
        //Demo: Traverse
        System. out.println("first traversal");
        while (true){             if (first==null){                 break;             }else {                 System.out.println(first);                 first=first.next;             }






        }
        System.out.println("last遍历");
        while (true){
            if (last==null){
                break;
            }else {
                System.out.println(last);
                last=last.pre;
            }
        }
    }
}

//Define a node class. The node object represents a node of a doubly linked list
class Node{     public Object item; //The place where data is actually stored     public Node next;     public Node pre;     public Node(Object name){         this.item=name;     }





    @Override
    public String toString() {
        return "Node item=" + item ;
    }
}
```

### 5. LinkedList underlying structure

```java
package com.demo.list;

import java.util.LinkedList;

public class LinkedListCRUD {
    public static void main(String[] args) {
        LinkedList linkedList = new LinkedList();
        linkedList.add("1");
        linkedList.add("2");

        System.out.println(linkedList.remove());//The first element is deleted by default
        System.out.println("linkedList="+linkedList);
    }
    /* 1. Constructor
            public LinkedList() {             }         2. At this time, the attribute of linkedList first = null last = null         3. Execute and add            public boolean add(E e) {                 linkLast(e);                 return true;             }         4. Add the new node to the last           void linkLast of the doubly linked list (E e) {                 final Node<E> l = last;                 final Node<E> newNode = new Node<>(l, e, null);                 last = newNode;                 if (l == null)













                    first = newNode;
                else
                    l.next = newNode;
                size++;
                modCount++;
            }
        5. Analysis of the deletion process
            5.1. Execute linkedList.remove();//The first element is deleted by default
            5.2 Execute remove()
                public E remove( ) {                       return removeFirst();                 }             5.3 Execute removeFirst()                 public E removeFirst() {                     final Node<E> f = first;                     if (f == null)                         throw new NoSuchElementException();                     return unlinkFirst(f);








                }
            5.4 Execute unlinkFirst() to remove the first node of the doubly linked list pointed to by f
            private E unlinkFirst(Node<E> f) {                 // assert f == first && f != null;                 final E element = f.item ;                 final Node<E> next = f.next;                 f.item = null;                 f.next = null; // help GC                 first = next;                 if (next == null)                     last = null;                 else                     next.prev = null;                 size--;                 modCount++;                 return element;             }      */














}
```

### 6. Comparison between ArrayList and LinkedList

![Comparison between ArrayList and LinkedList](D:\study\Java_study\image\Comparison between ArrayList and LinkedList.png)

# 5. Set interface

## 1. Basic introduction to Set interface

·Unordered (the order of addition and removal is inconsistent), no index

·Duplicate elements are not allowed, containing at most one null

·Like the List interface, it inherits from the Collection interface, so the common methods are the same as the list

·The traversal methods of the set interface are only iterators and enhanced for loops

```java
public static void main(String[] args) {     //1. Use the implementation class HashSet of the Set interface to explain the methods of the Set interface     //2. The object of the implementation class of the set interface (Set interface object) cannot To store duplicate elements, you can add a null     //3. The data stored by the Set interface is unordered (the order of addition and the order of removal are inconsistent)     //4. Note: Although the order of removal is not the order of addition, it is a fixed     HashSet set = new HashSet();     set.add("1");     set.add("2");     set.add(2);








    set.add(null);
    set.add(null);


    System.out.println(set);
    set.add("测试");
    System.out.println(set);

    //Traverse
    System.out.println("======Use iterator=====");
    Iterator iterator = set.iterator();
    while (iterator.hasNext()) {         Object obj = iterator.next ();         System.out.println("obj="+obj);     }     System.out.println("======Enhanced for loop=====");     for (Object obj:set) {         System.out.println("obj="+obj);     }     //set interface object cannot obtain the object through index } ```









## 2、HashSet

The bottom layer of HashSet is HashMap

```java

        //1. Constructor source code
        /*
            public HashSet() {         map = new HashMap<>();     }          */         //2. Nulls can be stored, but there is only one null         //3.HashSet does not guarantee that the elements are ordered , depends on the result of determining the index after hashing. (That is, there is no guarantee that the order of storing elements and taking out elements is consistent) ```





The bottom layer of HashMap is (array + linked list + red-black tree)

To add an element, first get the hash value - which will be converted into -> index value

Find the storage data table table and see if there are elements stored at this index position.

If not, just join

If there is, call equals to compare. If they are the same, give up adding. If they are not the same, add them to the end.

**In java8, if the number of elements in a linked list exceeds TREEIFY_THRESHOLD (default is 8), and the size of the table >=MIN_TREELFY_CAPACITY(64). It will turn into a tree (red-black tree)**

Guess you like

Origin blog.csdn.net/m0_62945506/article/details/122257406