java collection details

Posted by jeffz2008 on Sat, 30 Oct 2021 13:27:45 +0200

java collection details

Collection - an object used to store bulk data, which can be regarded as a variable length array

├--List Interface: elements are saved in order according to the order of entry, and can be repeated
	│--—- LinkedList Interface implementation class, linked list, insert and delete, no synchronization, thread unsafe
	│--—- ArrayList Interface implementation class, array, random access, no synchronization, thread unsafe
	│--—- Vector Interface implementation, class array, synchronization, thread safety
	│ ---—- Stack yes Vector Class implementation class
│--Set Interface: received only once, non repeatable, and sorted internally
	│--—-HashSet use hash Table (array) storage elements
	│---- LinkedHashSet The linked list maintains the insertion order of elements
	│ --—-TreeSet The bottom layer is implemented as a binary tree, and the elements are arranged in order

List interface

Orderly and repeatable stored values

Some methods are added to the List collection to manipulate the collection elements according to the index

・ void add(int index, Object ele) / / add an element at the specified location

・ boolean addAll(int index, Collection eles) / / add a large number of elements at the index position

・ Object get(int index) / / query the element at the specified location

・ int indexOf(Object obj) / / query the specified element and return the location. If not found, return - 1

・ int lastIndexOf(Object obj) / / query the specified element back and return the location

・ Object remove(int index) / / delete the element at the specified location

・ Object set(int index, Object ele) / / modify the element at the specified position

List subList(int fromIndex, int toIndex) / / get the subset and of the specified range


Array structure is used to store elements, which is used when there are many query operations

ArrayList is thread unsafe, while Vector is thread safe. Even to ensure the thread safety of List collection, Vector is not recommended

    public void test3(){
        List list = new ArrayList();

        list.set(1, "bbbbb");


        List list1 = list.subList(1, 3);
    public void test2(){
        List list = new ArrayList();




    public void test1(){
        List list = new ArrayList();

        list.add(1, "ff");


        List list2 = Arrays.asList(1,2,3);
        list.addAll(1, list2);

        Object o = list.get(4);


The linked list structure is used to store elements, which is used when frequently inserting or deleting elements

Unique methods:

・ void addFirst(Object obj) / / add an element in the header

・ void addLast(Object obj) / / add an element at the end

・ Object getFirst() / / take the header element

・ Object getLast() / / take the tail element

・ Object removeFirst() / / delete and get the header element

・ Object removeLast() / / delete and get the tail element

public void test1(){
    LinkedList ll = new LinkedList();



    Object first = ll.getFirst();

    Object o = ll.removeFirst();

[CC, BB, AA, DD]
[BB, AA, DD]
[BB, AA]

set interface

Non repeatable, internal sorting


HashSet stores the elements in the set according to the Hash algorithm, so it has good access and search performance.

HashSet has the following characteristics:

The order of elements cannot be guaranteed

HashSet is not thread safe

Collection elements can be null

The basis for judging whether an element exists is to compare hashCode() first. If hashCode does not exist, it will be stored directly
If hashCode exists, compare the contents of the two objects through equals().

Reduce hash conflict: add a new linked list at the current hashCode value, and store different objects behind the same hashCode value, so as to ensure the uniqueness of elements

Note: when rewriting hashcode and equals methods, they must be consistent! That is, when two objects are identical, the generated hashcode must be the same, and equals must be true

Storage form:

HashSet stores data in the form of array + linked list. The initial value of the array is 16 and the loading factor is 0.75. In other words, when the hash table is filled to 75%, the capacity will be expanded, which is twice the original length

LinkedHashSet: it is a subclass of HashSet. Compared with HashSet, it has more order of linked list maintenance elements. The traversal efficiency is higher than that of HashSet, and the addition and deletion efficiency is lower than that of HashSet


The main function of TreeSet is to sort

There are two sorting methods: natural sorting and custom sorting. By default, TreeSet adopts natural sorting

public void treeTest()
        TreeSet treeSet = new TreeSet();
[21, 32, 43, 54, 78] //sort
public class Person implements Comparable{

    private String name;
    private Integer age;

    public Person(String name, int age) { = name;
        this.age = age;
treeSet.add(new Person("jk",23));
treeSet.add(new Person("ek",45)); 
System.out.println(treeSet); //report errors

When comparing objects, an error will be reported because you don't know which comparison to use

1. Natural sorting
2. Comparator sorting

Natural sort operation:
1. Implement Comparable interface
2. Rewrite the compareTo method in the Comparable interface

public int compareTo(Object o) {
    if (o instanceof Person)
        Person p=(Person) o;
        int n=0;
        if (this.getAge().equals(this.getAge()))//equals for reference type
            return this.getName().compareTo(p.getName());
        return this.getAge().compareTo(p.getAge()); //If age is int, return this.getAge()-p.getAge();
    return  0;
treeSet.add(new Person("jk",23));
treeSet.add(new Person("ek",45));
treeSet.add(new Person("bf",53));
treeSet.add(new Person("gd",23));
treeSet.add(new Person("ek",45));
[Person(name=bf, age=53), 
Person(name=ek, age=45), 
Person(name=gd, age=23),
Person(name=jk, age=23)]

Custom sorting
1. Declare a class to implement Comparator interface
2. Implement the abstract method compare(Object o1, Object o2) in the interface
3. Pass the instance of the implementation class as a parameter to the constructor of TreeSet

Use the int compare(T o1,T o2) method to compare the sizes of o1 and o2: if the method returns a positive integer, it means that o1 is greater than o2; If 0 is returned, it means equal; Returns a negative integer indicating that o1 is less than o2.

public class MyComparator implements Comparator {
    public int compare(Object o1, Object o2) {
        if(o1 instanceof Person && o2 instanceof Person){
            Person p1 = (Person) o1;
            Person p2 = (Person) o2;

                return p1.getName().compareTo(p2.getName());
            return p1.getAge().compareTo(p2.getAge());
        return 0;
MyComparator my = new MyComparator();
TreeSet treeSet = new TreeSet(my);

3) Traversal of sets

1. Enhanced for loop

2. Using Iterator iterators

package java.util;
public interface Iterator<E> {
    boolean hasNext();//Determines whether the next object element exists

    E next();//Get next element

    void remove();//Removing Elements 
public void test() {
        List list = new ArrayList();
        Iterator it = list.iterator();
        while (it.hasNext()) {

Note: when using Iterator, it is forbidden to change the size structure of the traversed container. For example, when iterating with Iterator, if add and remove operations are performed on the collection, a ConcurrentModificationException exception will appear. Because before you iterate, the Iterator has been created through list.itertor(). If you change the container size of the list during the iteration, Java will give an exception. Because the Iterator object cannot actively synchronize the changes made by the list at this time, Java will think that such an operation is thread unsafe

4)ListIterator interface

Main differences between Iterator and ListIterator:

1, ListIterator and iterator both have hasNext() and next() methods, which can realize sequential backward traversal. However, ListIterator has hasPrevious() and previous() methods, which can realize reverse (sequential forward) traversal. Iterator can't.

2, ListIterator can locate the current index position, and nextIndex() and previousIndex() can be implemented. Iterator does not have this feature.

3, ListIterator has an add() method that can insert objects into the List, but Iterator cannot.

4, Can delete objects, but ListIterator can modify objects, and set() method can. Iterator can only traverse and cannot be modified. Because of these functions of ListIterator, you can operate List data structures such as LinkedList.

//He drew a picture after the great God


  |--HashMap: yes Map Typical implementation classes of interfaces
  |--Hashtable: Is an ancient implementation that is thread safe and therefore inefficient. Not recommended
        |--Properties:Properties file for operation
  • Map and Collection exist side by side. Used to save data with mapping relationship: key value
  • The key and value in the Map can be data of any reference type
  • The key in the Map is stored in a Set and cannot be repeated. That is, the class corresponding to the same Map object must override the hashCode() and equals() methods.
  • String class is often used as the "key" of Map.
  • There is a one-way one-to-one relationship between key and value, that is, a unique and definite value can always be found through the specified key

Common methods:

Object get(Object key) : according to key Get the corresponding value
boolean containsKey(Object key) :Determine whether there is a key
boolean containsValue(Object value) :Determine whether there is a value
int size() : Get current Map How many pairs are there
boolean isEmpty()
boolean equals(Object obj) : Judge two Map Are they exactly equal
 Add and delete operations:
Object put(Object key,Object value) :add to
Object remove(Object key) : according to key Deletes the specified key value pair
void putAll(Map t) : take t Add all key value pairs in the current Map in
void clear() : empty Map All key value pairs in

Traversal method of Map:

  • Method 1: get the Set composed of all keys in the Map. keySet()
  • Method 2: get the Collection composed of all values in the Map. values()
  • Method 3: get the Set composed of all entries in the Map (which is the internal class of the Map. An Entry corresponds to a Key and a value)
//Mode 1
public void test2() {

    Map m = new HashMap();

    Set set = m.keySet();
    for (Object o : set)
        Object value = m.get(o);
//Mode II
    Collection values = m.values();
    Iterator it = values.iterator();
    while (it.hasNext())
//Mode III
    Set en = m.entrySet();
    for (Object o : en)
        Map.Entry entry= (Map.Entry) o;
        Object key = entry.getKey();
        Object value = entry.getValue();
        System.out.println(key +"="+value);

1)HashMap :

  • Before JDK8, HashMap was composed of array + linked list. Array was the main body of HashMap, and linked list was mainly used to solve hash conflicts ("zipper method" to solve conflicts).
  • After JDK8, there are great changes in resolving hash conflicts. When the length of the linked list is greater than the threshold (8 by default), the linked list is transformed into a red black tree to reduce the search time.

HashMap is the most frequently used implementation class of Map interface.

Null keys and null values are allowed. Like HashSet, the mapping order is not guaranteed.

HashMap judges that two keys are equal according to the following criteria: the two keys return true through the equals() method, and the hashCode value is also equal.

HashMap judges that two value s are equal by returning true through the equals() method

2) LinkedHashMap

LinkedHashMap is a subclass of HashMap

Similar to LinkedHashSet, LinkedHashMap can maintain the iteration order of Map: the iteration order is consistent with the insertion order of key value pairs


Sorting of TreeMap keys:

  • Natural sorting: all keys of TreeMap must implement the Comparable interface, and all keys should be objects of the same class, otherwise ClasssCastException will be thrown

  • Custom sorting: when creating a TreeMap, a Comparator object is passed in, which is responsible for sorting all keys in the TreeMap. At this time, the key of the Map is not required to implement the Comparable interface

  • TreeMap judges the equality of two keys: two keys return 0 through the compareTo() method or the compare() method.

  • If the user-defined class is used as the key of TreeMap, the class needs to override the equals() and hashCode() methods, and when the equals() method returns true, the compareTo() method should return 0

Note: the bottom layer of HaspSet is haspmap, and the bottom layer of TreeSet is TreeMap, so the implementation method of TreeMap is basically the same as TreeSet


Collections is a tool class that operates on collections such as Set, List, and Map

Sorting operations: (all static Method)
➢reverse(List): reversal List Order of elements in
➢shuffle(List): yes List Random sorting of collection elements
➢sort(List): Assign to elements according to their natural order List The collection elements are sorted in ascending order
➢sort(List,Comparator): According to the specified Comparator Generated sequence pair List Sort collection elements
➢swap(List,int, int): Will specify list In the collection i At element and j Exchange elements at
 Find, replace
➢Object max(Collection): Returns the largest element in a given set according to the natural order of the elements
➢Object max(Collection,Comparator): according to Comparator Returns the largest element in a given collection in the specified order
➢Object min(Collection)
➢Object min(Collection,Comparator)
➢int frequency(Collection,Object): Returns the number of occurrences of the specified element in the specified collection
➢void copy(List dest,List src): take src Copy content from to dest in
➢boolean replaceAll(List list,Object oldVal,Object newVal): Replace with new value List All old values of the object
public void test3(){
    List list = new ArrayList();

    Collections.swap(list, 1, 3);
[55, 44, 33, 22, 11]
[44, 55, 11, 22, 33]
[11, 22, 33, 44, 55]
[11, 44, 33, 22, 55]

Collection is a very important knowledge point. Here are just some examples. It also needs repeated review and grinding in the later stage. Come on!!!

Topics: Java Back-end