Single column collection Collection and its subclasses

Common singleton collections

  • Preface
  • Collection collection
  • List collection
    • ArrayList collection
    • LInkedList collection
  • Set set
    • HashSet collection
    • TreeSet collection

Foreword

Here, each collection traversal method and method is repeated, so only the traversal methods and methods will be discussed in the Collection collection. If there are unique collection traversal methods and methods, they will be discussed separately. Other duplicates will only be discussed in the Collection collection.

Collection

The so-called single-column collection is an element in the collection that only stores one value, and the Collection collection is the ancestor of all singleton collections. All its methods can be used in the descendants of Collection.

  • Commonly used methods of Collection collections
Method Function
add(E e) Add an element and return true if added successfully
clear() Clear the elements in the collection
isEmpty() Determine whether the collection is empty. If it is empty, it returns true, otherwise it returns false
sizse() Get the size of the collection
contains(Object obj) Determine whether the collection contains an element
remove(E e) Delete an element. If there are multiple duplicate elements, only delete the first one
toArray() Convert the collection into an array, the array is of type Object
public class Demo01 {<!-- -->
    public static void main(String[] args) {<!-- -->
        Collection<String> list = new ArrayList<>();
        // add(E e) adds an element and returns true if the addition is successful.
        list.add("ganqiao");

        // clear() clears the collection elements
        list.clear();
        System.out.println(list);

        // isEmpty() determines whether the collection is empty. If it is empty, it returns true, otherwise it returns false.
        System.out.println(list.isEmpty());
        
        // size() gets the collection length
        int size = list.size();
        
        // contains(Object obj) determines whether the collection contains an element
        list.add("Caojia");
        System.out.println(list.contains("Caojia"));
        
        // remove(E e) deletes an element. If there are multiple duplicate elements, only delete the first one.
        list.remove("Caojia");
        
        // toArray() converts the collection into an array, which is of type Object
        Object[] array = list.toArray();
    }
}

  • Collection traversal method

Iterator

  1. Create an iterator object: Iterator iterator = list.iterator();
  2. Use a while loop to determine whether there is an element at the current position
  3. Use iterator.next() to take out the element at the current position and point the pointer to the next element position
  4. Be careful not to directly output multiple iterator.next() when traversing, because this may cause out-of-bounds errors in the traversal
  5. There is a problem with concurrent modification exceptions
public class Demo02 {<!-- -->
    public static void main(String[] args) {<!-- -->
        Collection<String> list = new ArrayList<>();
        list.add("ganqiao");
        list.add("Caojia");
        list.add("五代");
        list.add("一一");

        Iterator<String> iterator = list.iterator();
        while (iterator.hasNext()){<!-- -->
            String str = iterator.next();
            System.out.println(str);
        }
    }
}

Enhance for loop

  1. The enhanced for loop is essentially a simplified way of writing an iterator, which can be used to traverse collections and arrays
  2. There is a problem with concurrent modification exceptions
public class Demo02 {<!-- -->
    public static void main(String[] args) {<!-- -->
        Collection<String> list = new ArrayList<>();
        list.add("ganqiao");
        list.add("Caojia");
        list.add("五代");
        list.add("一一");

        for (String s : list) {<!-- -->
            System.out.println(s);
        }
    }
}

forEach(Lambda)

  1. Collection.forEach(collection element -> {code})
  2. The bottom layer is also an iterator, and there will also be problems with concurrent modification exceptions.
public class Demo02 {<!-- -->
    public static void main(String[] args) {<!-- -->
        Collection<String> list = new ArrayList<>();
        list.add("ganqiao");
        list.add("Caojia");
        list.add("五代");
        list.add("一一");

        list.forEach(item -> System.out.println(item));
    }
}

List collection

The List collection is a sub-interface of the Collection collection. There are two commonly used implementation classes under it, ArrayList and LInkedList. The elements in them are ordered, repeatable, and indexed

  • Unique methods of List collection
Method Function
add(int index, E element) Insert an element at a certain index position
remove(int index) Delete the element according to the index and return the deleted element
get(int index) Returns the element at the specified position in the collection
set(int index, E element) Modify the element at the specified index position. After the modification is successful, return the original data
public class Demo02 {<!-- -->
    public static void main(String[] args) {<!-- -->
        List<String> list = new ArrayList<>();
        list.add("Liu Bei");
        list.add("Zhang Fei");
        list.add("Guan Yu");
        list.add("Zhao Yun");
        list.add("Ma Chao");

        // add(int index, E element) inserts an element at a certain index position
        list.add(0,"Cao Cao");

        // remove(int index) deletes the element according to the index and returns the deleted element
        list.remove(0);

        // get(int index) returns the element at the specified position in the collection
        String s = list.get(3);

        // set(int index, E element) modifies the element at the specified index position. After the modification is successful, the original data is returned
        list.set(1,"Cao Zhi");
    }
}

  • Unique traversal method of List collection

for loop

public class Demo02 {<!-- -->
    public static void main(String[] args) {<!-- -->
        List<String> list = new ArrayList<>();
        list.add("Liu Bei");
        list.add("Zhang Fei");
        list.add("Guan Yu");
        list.add("Zhao Yun");
        list.add("Ma Chao");

        for (int i = 0; i < list.size(); i + + ) {<!-- -->
            System.out.println(list.get(i));
        }
    }
}

ArrayList collection

The bottom layer of the ArrayList collection stores data through arrays. It uses a parameterless constructor to create an ArrayList collection, and then creates an array with a default length of 0 at the bottom. When adding the first element, the bottom layer will create a new array with a length of 10 to replace the old array. , when the collection is full of 10 elements, the underlying array will be expanded by 1.5 times. If multiple elements are added at a time and the 1.5 times expansion cannot accommodate it, the length of the new array shall be subject to the actual

  • Advantages and Disadvantages of ArrayList
  1. Querying data through indexes is fast. When querying data, the address value and index are used to locate the data. This is because the underlying layer is an array.
  2. Deletion efficiency is low. This is because the bottom layer is an array. When deleting data, you may have to move the following elements to the front, which will affect efficiency.
  3. Addition efficiency is extremely low. If the capacity is sufficient, the subsequent data may need to be moved backward; if the capacity is insufficient, the array must be expanded, that is, an array must be redefined, and the data may be added one by one.

  • Application scenarios of ArrayList
  1. When you need to query data through an index, for example, searching for data based on a random index will be very efficient, or when the amount of data is not very large, the query will be fast.
  2. When the amount of data is large and frequent addition and deletion operations are required, it is not suitable to use ArrayList to store data.

LInkedList collection

The bottom layer of the LInkedList collection is based on a doubly linked list. In addition to the head and tail nodes, other stages store the address values of the front and rear nodes. Therefore, the speed of searching for data through the LInkedList collection is faster, but the speed of searching for data is still very slow compared to the ArrayList.

  • Advantages and Disadvantages
  1. Adding and deleting data is fast, because LInkedList is based on a doubly linked list, so when adding or deleting elements, you only need to change the addresses stored in the elements’ front and back nodes.
  2. Querying elements in LInkedList is slow, but querying the head node is very fast.
Method Function
addFirst(E e) Insert the specified element at the head of the list
addLast(E e) Insert the specified element at the end of the list
getFirst() Returns the first element of the list
getLast() Return the last element of the list
removeFirst() Remove the first element of the list
removeLast() Remove the last element of the list
public class Demo03 {<!-- -->
    public static void main(String[] args) {<!-- -->
        LinkedList<String> list = new LinkedList<>();

        // addFirst(E e) inserts the specified element at the head of the list
        list.addFirst("Guangzhou");
        list.addFirst("Shenzhen");
        System.out.println(list);
        System.out.println("--------------------");

        // addLast(E e) inserts the specified element into the end of the list
        list.addLast("Hangzhou");
        list.addLast("Shanghai");
        System.out.println(list);
        System.out.println("--------------------");

        // getFirst() returns the first element of the list
        String first = list.getFirst();
        System.out.println(first);
        System.out.println("--------------------");

        // getLast() returns the last element of the list
        String last = list.getLast();
        System.out.println(last);
        System.out.println("--------------------");

        // removeFirst() removes the first element of the list
        list.removeFirst();
        System.out.println(list);
        System.out.println("--------------------");

        // removeLast() removes the last element of the list
        list.removeLast();
        System.out.println(list);
    }
}

  • Application scenarios of LInkedList
  1. Queue, first in first out, frequent operations on the head and tail of the queue
  2. Stack, first in, last out

Set collection

Set is a sub-interface of Collection. It has two implementation classes, namely HashSet and TreeSet. The elements in the Set collection are unordered, non-repeatable, and unindexed

  • no special method
  • No special traversal method

Hash value

  1. Every object in Java has a hash value, which is an int type and is data
  2. Each object can obtain the hash value of the object through the hashCode() method provided by the Object class.
  3. Under normal circumstances, the hash value of each object is different, but because the hash value is an int type data with a limited value range, it is possible that the hash values of two objects are the same. This situation is called a hash collision.

HashSet collection

The elements in the HashSet collection are non-repeating, unordered, and unindexed. The bottom layer is implemented based on a hash table. Before JDK8, the hash table was array + linked list. Starting from JDK8, the hash table is array + linked list + red-black tree

  • HashSet collection’s deduplication mechanism for objects with the same content
  1. In the HashSet collection, it is believed that as long as the hash values of two objects are different, they are two different objects. However, when we create two objects with the same content, the effect of deduplication cannot be achieved using HashSet.
  2. To remove duplicate objects with the same content, we must override the equals and hashCode methods in the object class to complete the deduplication.
  • The principle of adding elements to the hash table collection
  1. First calculate the position of the object in the array through the hash value of the object.
  2. If there is no element at that position, add it directly.
  3. If there is an element at this position, use equals() to compare. If they are the same, they will not be added. If they are not the same, they will be divided into two situations. The first is that before JDK8, the new element replaced the old element and became the header node, while the old element was hung below the new element; the second is that starting from JDK8, the new element is directly hung at the end of the linked list.

LinkedHashSet

The elements in the LInkedHashSet collection are ordered, non-repeating, and non-indexed. Its bottom layer is a hash table based on arrays, singly linked lists, red-black trees, and double linked lists.

TreeSet collection

The elements in the TreeSet collection are non-repeating, non-indexable, and sortable (the default is ascending order). The underlying principle is based on red-black trees.

  • sort
  1. When the incoming set element type is a basic data type, it is sorted directly according to the value of the basic data type. String types are sorted according to the first letter or the following alphabetical order.
  2. When the incoming element is a reference data type, we need to customize the sorting rules. There are two ways:
  • Method 1: Let the class implement the Compareble interface and rewrite the comparaTo method to formulate rules
public class Demo04 {<!-- -->
    public static void main(String[] args) {<!-- -->
        TreeSet<Student> list = new TreeSet<>();
        list.add(new Student("Zhang San",19));
        list.add(new Student("李思",16));
        list.add(new Student("王五",20));
        list.add(new Student("Zhao Liu",18));

        list.forEach(item -> System.out.println(item));
    }
}

class Student implements Comparable<Student> {<!-- -->
    private String name;
    private int age;

    public Student() {<!-- -->
    }

    public Student(String name, int age) {<!-- -->
        this.name = name;
        this.age = age;
    }

    /**
     * Obtain
     * @return name
     */
    public String getName() {<!-- -->
        return name;
    }

    /**
     * set up
     * @param name
     */
    public void setName(String name) {<!-- -->
        this.name = name;
    }

    /**
     * Obtain
     * @return age
     */
    public int getAge() {<!-- -->
        return age;
    }

    /**
     * set up
     * @param age
     */
    public void setAge(int age) {<!-- -->
        this.age = age;
    }

    public String toString() {<!-- -->
        return "Student{name = " + name + ", age = " + age + "}";
    }

    @Override
    public int compareTo(Student o) {<!-- -->
        return this.getAge() - o.getAge();
    }
}

  • Method 2: By calling the parameterized constructor of the TreeSet collection, you can set the Comparator object (comparator object, used to formulate comparison rules)
public class Demo04 {<!-- -->
    public static void main(String[] args) {<!-- -->
        TreeSet<Student> list = new TreeSet<>((o1, o2) -> o1.getAge() - o2.getAge());
        list.add(new Student("Zhang San",19));
        list.add(new Student("李思",16));
        list.add(new Student("王五",20));
        list.add(new Student("Zhao Liu",18));

        list.forEach(item -> System.out.println(item));
    }
}

class Student {<!-- -->
    private String name;
    private int age;

    public Student() {<!-- -->
    }

    public Student(String name, int age) {<!-- -->
        this.name = name;
        this.age = age;
    }

    /**
     * Obtain
     * @return name
     */
    public String getName() {<!-- -->
        return name;
    }

    /**
     * set up
     * @param name
     */
    public void setName(String name) {<!-- -->
        this.name = name;
    }

    /**
     * Obtain
     * @return age
     */
    public int getAge() {<!-- -->
        return age;
    }

    /**
     * set up
     * @param age
     */
    public void setAge(int age) {<!-- -->
        this.age = age;
    }

    public String toString() {<!-- -->
        return "Student{name = " + name + ", age = " + age + "}";
    }
}