Java collection Collection interface (super detailed explanation)

1. Collection

(Daily study notes, please don’t comment if you don’t like them. Corrections and discussions are welcome!)

What is Collection interface?

There is a large class of collection in Java. Collection is a single-column collection in the collection class. It is the parent interface of all single-column collections. The sub-interfaces of Collection include List interface and Set interface. This means that all single-column collection classes inherit this interface. It defines some basic methods common to collections, such as adding, deleting, querying, and traversing elements.

Insert image description here

Features of Collection sub-interface:
1. Similarities:
  • They are all sub-interfaces of Collection, so they all inherit the Collection interface and define all methods of the Collection interface.
  • They are all asynchronous. In a multi-threaded environment, the operations they perform are not atomic, so they are designed as concurrent classes.
2. Differences:
  • List interface:
    • The elements are stored in order , and the order in which List elements are stored and retrieved is consistent, that is, they are stored and retrieved in the order in which they are added.
    • Elements are repeatable and can contain repeating elements: Listrepeated elements are allowed to be stored.
    • Elements with indexes : The List interface defines some indexed methods, such as get(int index)obtaining elements at a specified position, add(int index, E element)adding elements at a specified position, etc.
  • Set interface:
    • The elements are stored in an unordered manner , and Setthe order in which elements are stored and added has nothing to do with it, that is, the order in which they are stored and retrieved cannot be guaranteed.
    • Elements cannot be repeated : SetDuplicate elements are not allowed to be stored, and the same element will only be stored once.
    • Can store null elements: SetA null element can be stored, but only once.
Collection as a parent class has those methods:
Collection<String> c = new ArrayList<>();

//向集合中添加元素,如果添加成功返回true,如果集合因为添加元素而改变,其他集合也应该改变。
c.add(E e);

//从集合中删除元素,如果删除成功返回true,如果集合因为删除元素而改变,其他集合也应该改变。
c.remove(Object o);

// 检查集合中是否包含指定元素,如果包含返回true。
c.contains(Object o);

// 返回集合中元素的数量。
c.size();

//检查集合是否为空,如果为空返回true。
c.isEmpty();

//返回一个迭代器,用于遍历集合中的元素。
Iterator<String> it = c.iterator();
while (it.hasNext()) {
    
    //判断集合中还有没有没有被遍历 的元素
	String str = it.next();//获取下一个没有被遍历的元素
}

//返回一个包含集合中所有元素的数组。
c.toArray();

//移除集合中的所有元素,使集合为空。
c.clear();
Collection, as a parent interface, has the following implementation classes:
  1. ArrayList: Based on array implementation, it can quickly and randomly access elements, but when inserting or deleting elements, the entire element at the insertion or deletion position needs to be moved back or forward, so the efficiency is low.
  2. LinkedList: Based on linked list implementation, you can quickly insert or delete elements at both ends of the list, but it is less efficient when accessing elements randomly.
  3. HashSet: Based on hash table implementation, it can quickly find elements, but it is less efficient when dealing with repeated elements.
  4. TreeSet: Based on red-black tree implementation, it can keep elements in order, but the efficiency of inserting and deleting elements is low.
  5. LinkedHashSet: Based on hash table and linked list implementation , it can quickly find elements and keep elements in order, but it is less efficient when dealing with repeated elements.

In addition, there are implementation classes such as Vector and Stack, but they have been marked as obsolete or deprecated.

                                 ----分割线----

2. List

Implementation class: ArrayList

ArrayListIt is an implementation class in the Java collection framework. It is implemented based on dynamic arrays and can store any type of data and can automatically expand.

Features overview :
  1. Capacity can be dynamically expanded: ArrayListthe capacity can be dynamically increased as needed. When the number of elements exceeds the current capacity, a larger internal array will be automatically allocated and the original elements will be copied to the new array.
  2. Supports fast random access: Because it is based on dynamic array implementation, ArrayListit supports fast random access and can directly access elements through indexes, with a time complexity of O(1).
  3. Support batch operations: ArrayListProvides a series of add()methods to add multiple elements at one time, improving the efficiency of operations.
  4. Non-thread safety: ArrayListIt is not thread-safe. If multiple threads modify it at the same time ArrayList, data inconsistency may occur.
Common usage of ArrayList:
// 使用多态创建ArrayList对象,其父类为List,子类为ArrayList。
List<String> list = new ArrayList<>();

// 添加元素
list.add(1);
list.add(1, 2); // 在指定位置插入元素

// 获取元素
String apple = list.get(0); // 获取第一个元素

// 删除元素
list.remove(0); // 删除第一个元素

//替换指定位置的元素
list.set(0, 3);

//查询指定元素的索引
int index = list.indexOf(2);

//判断列表是否为空
boolean isEmpty = list.isEmpty();

//获取列表元素数量
int size = list.size();

//将列表转换为数组
Integer[] toArray = list.toArray(new Integer[0]);

// 查询元素是否存在
boolean containsApple = list.contains(1);

// 清空列表
list.clear();
Implementation class: LinkedList

LinkedListIs an implementation class of the Java Collections Framework that allows direct access to its elements. It is a doubly linked list that allows quick insertion and deletion operations at the head and tail of the list.

Features overview:
  1. Dynamic Arrays : LinkedListDynamic arrays are used internally so it is faster than static arrays when doing element addition, deletion and query operations.
  2. Bidirectional insertion or deletion: Insertion and deletion can be performed from the head and tail , and LinkedListefficient insertion and deletion operations at the head and tail are supported because it is a doubly linked list.
  3. Not thread-safe: LinkedListIt is not thread-safe. If multiple threads modify it at the same time, it may cause data inconsistency.
Common uses of LinkedList:
// 使用多态创建LinkedList对象,其父类为List,子类为LinkedList。
List<String> list = new LinkedList<>();

// 在列表的末尾添加指定的元素。
add(E element);

//在指定位置插入指定的元素。
add(int index, E element); 

//移除列表中首次出现的指定元素。
remove(Object o);

//返回列表中包含指定元素的结果。
contains(Object o);

//返回首次出现的指定元素的索引。
indexOf(Object o);

//检查列表是否为空。
isEmpty();

//返回列表中的元素数量。
size();

//获取指定位置的元素。
get(int index);

//替换指定位置的元素。
set(int index, E element); 

                                 ----分割线----

3. Set

Implement class HashSet

HashSet is a data structure in Java that implements the Set interface. Set is a collection that does not allow the storage of duplicate elements, and the underlying layer usually encapsulates a hash table.

Feature overview
  1. Duplicate elements are not allowed to be stored: each element in the Set is unique, and duplicate elements are not allowed.
  2. Unordered: HashSet is an unordered set, that is, the stored elements are stored in a certain order, but the storage order of the elements has nothing to do with the actual order of the elements.
  3. The bottom layer encapsulates a hash table: HashSet is implemented based on a hash table, so the time complexity of its operations such as addition, deletion and query is usually O(1).
  4. Thread-unsafe: Since HashSet has no synchronization mechanism, it is not thread-safe. In a multi-threaded environment, if multiple threads modify HashSet at the same time, data inconsistency may occur.
  5. Allows storage of null values: Unlike List, Set allows storage of null values.
Common uses of HashSet:
//添加元素:使用`add(E e)`方法向Set中添加元素。如果元素已经存在,会被忽略,因为Set不允许重复元素。
HashSet<String> set = new HashSet<>();
set.add("apple");
set.add("banana");
set.add("cherry");

//删除元素:使用remove(Object o)方法从Set中删除指定元素。如果元素不存在,删除操作会返回false。
set.remove("banana");

//查询元素:使用contains(Object o)方法查询Set中是否包含指定元素。
boolean containsApple = set.contains("apple");

//获取元素个数:使用size()方法获取Set中的元素个数。
int size = set.size();

//清空Set:使用clear()方法移除Set中的所有元素。
set.clear();

//迭代Set:使用iterator()方法返回一个迭代器,可以用来遍历Set中的所有元素。注意,返回元素的顺序并不是特定的。
Iterator<String> iterator = set.iterator();
while (iterator.hasNext()) {
    
    
    System.out.println(iterator.next());
}
Implement class LinkedHashSet

LinkedHashSet is a subclass of HashSet and exists under the java.util package. It is a special kind of HashSet.

Feature overview
  1. Orderliness: The elements in LinkedHashSet are ordered, and it maintains the order of elements in the order in which they are added. This is because the underlying layer of LinkedHashSet uses a hash table and a linked list, where the linked list is used to ensure that the elements are stored and retrieved in the same order.

  2. Efficient performance : The underlying layer of LinkedHashSet uses a hash table to store elements, so insertion, deletion and search operations can be performed within O(1) time complexity. This makes LinkedHashSet perform better than ArrayList when frequent insertion, deletion and search operations are required.

  3. Duplicate elements are not allowed: Similar to HashSet, LinkedHashSet does not allow duplicate elements in the set. If you add duplicate elements, only one will be retained.

  4. Thread-unsafe: Similar to HashSet, LinkedHashSet is thread-unsafe.

Common uses of LinkedHashSet
LinkedHashSet<String> linkedHashSet = new LinkedHashSet<>();  
  
// 添加元素  
linkedHashSet.add("apple");  
linkedHashSet.add("banana");  
linkedHashSet.add("cherry");  
linkedHashSet.add("apple"); // 重复元素,会被忽略  
  
// 输出LinkedHashSet中的元素  
for (String element : linkedHashSet) {
    
      
	System.out.println(element);  
}  
//输出结果,其中LinkedHashSet是有序的,因此输出的元素顺序将与添加的顺序一致。
apple
banana
cherry
Implement class TreeSet

TreeSet is a class in Java. It belongs to the java.util package and is a subclass of the Set collection. It implements the SortedSet interface, so the elements in the TreeSet are always arranged in ascending order. . TreeSet is implemented based on binary trees .

Feature overview
  1. Orderliness : The elements in a TreeSet are arranged in a certain order. This order depends on the comparator provided when creating the TreeSet or the natural ordering of the elements themselves. If no comparator is provided, then the natural ordering of the elements themselves takes effect.
  2. Uniqueness : TreeSet does not allow storing duplicate elements.
  3. Thread-unsafe: TreeSet does not provide any thread-safe mechanism, so additional synchronization measures are required when used in a multi-threaded environment.
  4. Underlying data structure : The bottom layer of TreeSet uses a red-black tree data structure. The red-black tree is a self-balancing binary search tree that can complete insertion, deletion and search operations in O(log n) time complexity.

TreeSet is traversed according to the natural order of elements or the order defined by the comparator provided when creating TreeSet. TreeSet can be used for sorting, but the efficiency is lower than ArrayList because a binary search is required every time an element is inserted, and the time complexity is O(log n).

Common uses of TreeSet
//添加元素:使用add()方法向TreeSet中添加元素。
TreeSet<Integer> treeSet = new TreeSet<>();
treeSet.add(1);
treeSet.add(2);
treeSet.add(3);

//删除元素:使用remove()方法从TreeSet中删除元素。
treeSet.remove(2); // 从TreeSet中删除2

//查找元素:使用contains()方法查找TreeSet中是否包含指定元素。
boolean contains = treeSet.contains(1); // 返回true

//获取元素:使用first()方法获取TreeSet中的最小元素,使用last()方法获取TreeSet中的最大元素。

int first = treeSet.first(); // 返回TreeSet中的最小元素
int last = treeSet.last(); // 返回TreeSet中的最大元素

//清空TreeSet:使用clear()方法清空TreeSet中的所有元素。
treeSet.clear(); // 清空TreeSet

//遍历TreeSet:for-each循环遍历TreeSet中的所有元素。
for (Integer num : treeSet) {
    
    
    System.out.println(num);
}
//遍历TreeSet:迭代器遍历TreeSet中的所有元素。
Iterator<Integer> iterator = treeSet.iterator();
while (iterator.hasNext()) {
    
    
    System.out.println(iterator.next());
}
import java.util.Set;
import java.util.TreeSet;

/**
 * TreeSet进行排序需要实现两个步骤:
 * 	1.实现Comparable接口
 * 	2.重写该接口中的compareTo方法,就是重写排序规则
 */
public class TreeSet {
    
    
    public static void main(String[] args) {
    
    

        Set<Dog> set = new TreeSet<>();
        set.add(new Dog("nn",10));
        set.add(new Dog("bb",9));
        set.add(new Dog("hh",7));
        set.add(new Dog("pd",8));

        set.toString();
        System.out.println(set);
    }

}
//实现Comparable接口
class Dog implements Comparable<Dog>{
    
    
    String name;
    int age ;

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

    public Dog() {
    
    
    }

    //重写排序规则
    @Override
    public int compareTo(Dog o) {
    
    
        return this.age - o.age;
    }

    @Override
    public String toString() {
    
    
        return "Dog{" + name + "," + age + "}";
    }
}


//输出:[Dog{hh,7}, Dog{pd,8}, Dog{bb,9}, Dog{nn,10}]
                                 ----分割线----

4. Queue

Queue is a special data structure that follows the first-in-first-out (FIFO) principle. The Queue interface is in Java's java.util package and is a sub-interface of the Collection interface.

Insert image description here

Overview of queue features
  1. The queue is a linear structure that follows the first-in-first-out (FIFO) principle, that is, the element that enters the queue first will be deleted first .
  2. The queue only allows deletion operations on the front end of the table (front) and insertion operations on the back end (rear) of the table . This ensures the sequentiality of the queue, that is, the position of the elements in the queue will not change.
  3. The queue can perform efficient insertion and deletion operations because it uses a dynamic allocation strategy and can expand and contract as needed .
  4. Queues can be used to implement specific tasks, such as processing print tasks, implementing message queues, and inter-process communication.
Common uses of queues
import java.util.LinkedList;  
import java.util.Queue;  
  
public class Main {
    
      
    public static void main(String[] args) {
    
      
        // 创建一个队列  
        Queue<String> queue = new LinkedList<>();  
  
        // 入队操作  
        queue.add("Apple");  
        queue.add("Banana");  
        queue.add("Cherry");  
  
        // 输出队列的大小  
        System.out.println(queue.size());  // 输出:3  
  
        // 出队操作  
        System.out.println(queue.poll());  // 输出:Apple  
        System.out.println(queue.poll());  // 输出:Banana  
        System.out.println(queue.poll());  // 输出:Cherry  
  
        // 检查队列是否为空  
        System.out.println(queue.isEmpty());  // 输出:true  
    }  
}
Queue traversal

In a data structure like a queue, we cannot directly traverse the elements of the queue. This is because the queue is a first-in-first-out (FIFO) data structure, and the position of elements in the queue changes dynamically. When an element is fetched, it is removed from the queue without retaining any positional information for subsequent elements.

However, it is possible to iterate over the elements of a queue indirectly via:

  1. Use foreach loop to traverse
public class Main {
    
    
    public static void main(String[] args) {
    
    
        Deque<String> queue = new LinkedList<>();
        queue.add("Apple");
        queue.add("Banana");
        queue.add("Cherry");

        for (String item : queue) {
    
    
            System.out.println(item);
        }
    }
}
  1. Loop through using an Iterator
public class Main {
    
    
    public static void main(String[] args) {
    
    
        Queue<String> queue = new LinkedList<>();
        queue.add("Apple");
        queue.add("Banana");
        queue.add("Cherry");

        Iterator<String> iterator = queue.iterator();
        while (iterator.hasNext()) {
    
    
            System.out.println(iterator.next());
        }
    }
}
Sub-interface of Queue: Deque (double-ended queue)

Deque (double-ended queue) is a data structure that allows us to perform insertion and deletion operations at the front and back ends of the queue. Deque (double-ended queue) supports the FIFO principle, and the earliest added elements are removed first.

import java.util.Deque;
import java.util.LinkedList;

public class Main {
    
    
    public static void main(String[] args) {
    
    
        Deque<String> deque = new LinkedList<>();

        // 在后端添加元素
        deque.addLast("Apple");
        deque.addLast("Banana");
        deque.addLast("Cherry");

        // 在前端添加元素
        deque.addFirst("Orange");

        // 打印 deque 的内容
        System.out.println(deque); // 输出:["Orange", "Apple", "Banana", "Cherry"]

        // 移除前端元素并打印其值
        System.out.println(deque.removeFirst()); // 输出:Orange
        System.out.println(deque); // 输出:["Apple", "Banana", "Cherry"]

        // 移除后端元素并打印其值
        System.out.println(deque.removeLast()); // 输出:Cherry
        System.out.println(deque); // 输出:["Apple", "Banana"]
    }
}
                                 ----分割线----

5. Things to note:

The above introduces some common uses of Collection, including operations such as adding, deleting, searching, obtaining elements, and traversing. You need to pay attention to the following points when using Collection:

  1. Pay attention to the type of collection: Each collection type has its specific uses and limitations, and you should choose the appropriate collection type according to your needs. For example, when using ArrayList, you need to pay attention to its insufficient capacity. When using LinkedHashSet, you need to pay attention to the fact that it cannot guarantee the order of elements.
  2. Avoid NullPointerException: When using collections to store elements, you should avoid storing null objects to avoid throwing NullPointerException.
  3. Avoid modifications when traversing a collection: Modifying collection elements while traversing a collection may cause a ConcurrentModificationException. If you need to modify the collection elements during the traversal process, you can use the Iterator's remove() method.
  4. Pay attention to the capacity of the collection: When using collections of dynamic array types such as ArrayList, you should pay attention to the problem of insufficient capacity. When the capacity of the array is not enough to accommodate more elements, the expansion method needs to be used to increase the capacity.

Guess you like

Origin blog.csdn.net/weixin_57486248/article/details/132218200