Java List Series Collection

Keywords: Java list

Features of List Series Collection:

  • ArrayList, LinekdList: ordered, repeatable, indexed.
  • Ordered: the stored and retrieved elements are in the same order
  • Indexed: elements can be manipulated by indexing
  • Repeatable: stored elements can be repeated

Unique method of List Collection: because the List Collection supports index, it has many unique APIs for index operation, and the functions of other collections are inherited.

Method name

explain

void add(int index,E element)

Inserts the specified element at the specified location in this collection

E remove(int index)

Deletes the element at the specified index and returns the deleted element

E set(int index,E element)

Modify the element at the specified index and return the modified element

E get(int index)

Returns the element at the specified index

import java.util.ArrayList;
import java.util.List;

public class ListDemo1 {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("Java");
        list.add("java");
        list.add("MySQL");
        list.add("MySql");

        //2. Inserts an element at an index location
        list.add(2,"HTML");
        System.out.println(list);//[Java, java, HTML, MySQL, MySql]

        //3. Delete the element according to the index and return the deleted element
        System.out.println(list.remove(2));//HTML
        System.out.println(list);//[Java, java, MySQL, MySql]

        //4. Get element according to index: public E get(int index): returns the element at the specified position in the collection
        System.out.println(list.get(2));//MySQL

        //5. Modify the element at the index position: public E set(int index, E element)
        //Return the data before modification
        System.out.println(list.set(1,"Old tomato"));//java
        System.out.println(list);//[Java, old tomato, MySQL, MySql]
    }
}

The underlying principle of the implementation class of List:

  • The bottom layer of ArrayList is implemented based on array. According to the query elements, it is fast and the addition and deletion are relatively slow (relatively, actually OK).
  • The underlying LinkedList is based on a double linked list. Querying elements is slow, and adding and deleting beginning and end elements is very fast.

Traversal method of List collection:

  • iterator
  • Enhanced for loop
  • Lambda expression
  • for loop (because the List collection has an index)
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ListDemo2 {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("Java");
        list.add("java");
        list.add("MySQL");
        list.add("MySql");

        //1. for loop
        System.out.println("-----------------");
        for (int i = 0; i < list.size(); i++) {
            String ele = list.get(i);
            System.out.println(ele);
        }

        //2. Iterator
        System.out.println("------------------");
        Iterator<String> it = list.iterator();
        while (it.hasNext()){
            String ele = it.next();
            System.out.println(ele);
        }

        //3,foreach
        System.out.println("------------------");
        for (String s : list) {
            System.out.println(s);
        }

        //4. Lambda expression
        System.out.println("--------------------");
        list.forEach(s -> {
            System.out.println(s);
        });
    }
}

The underlying principle of ArrayList set:

  • The bottom layer of ArrayList is based on array: locate element blocks according to the index, and shift elements when adding or deleting.
  • When creating a collection for the first time and adding the first element, create an array with a default length of 10 at the bottom. Use size to record the number of current elements and the insertion position of the next element. If the capacity exceeds, it will be expanded by 1.5 times the current capacity.

LinkedList features:

  • The underlying data structure is a double linked list, the query is slow, and the speed of head and tail operation is very fast, so there are many unique API s for head and tail operation.

Unique features of the LinkedList collection:

Method name

explain

public void addFirst(E e)

Inserts the specified element at the beginning of the list

public void addLast(E e)

Appends the specified element to the end of this list

public E getFirst()

Returns the first element in this list

public E getLast()

Returns the last element in this list

public E removeFirst()

Removes and returns the first element from this list

public E removeLast()

Removes and returns the last element from this list

import java.util.LinkedList;

public class ListDemo3 {

    public static void main(String[] args) {
        //Stack
        LinkedList<String> stack = new LinkedList<>();
        //stack.addFirst() is written in stack.push()
        stack.addFirst("First bullet");//stack.push("first bullet");
        stack.addFirst("Second bullet");//stack.push("second bullet");
        stack.addFirst("Third bullet");//stack.push("third bullet");
        stack.addFirst("Fourth bullet");//stack.push("fourth bullet");
        System.out.println(stack); //[Fourth bullet, third bullet, second bullet, first bullet]

        //Out of the stack, pop up the stack.pop(), which says stack.removeFirst()
        System.out.println(stack.removeFirst());//Fourth bullet
        System.out.println(stack.pop());//Third bullet
        System.out.println(stack.pop());//Second bullet
        System.out.println(stack);//[first bullet]


        //queue
        LinkedList<String> queue = new LinkedList<>();
        queue.addLast("1 number");
        queue.addLast("2 number");
        queue.addLast("3 number");
        queue.addLast("4 number");
        System.out.println(queue);//[1, 2, 3, 4]

        //Out of the team
        System.out.println(queue.removeFirst());//No. 1
        System.out.println(queue.removeFirst());//No. 2
        System.out.println(queue.removeFirst());//No. 3
        System.out.println(queue);//[No. 4]
    }
}

Concurrent modification exception problem of a set: when we find an element from the set and delete it, there may be a concurrent modification exception problem.

Problematic traversal:

  • This can occur when an iterator traverses a collection and deletes elements directly from the collection.
  • Enhanced for loops may occur when traversing a collection and directly deleting elements from the collection.

Traversal with no problem deleting elements:

  • The iterator traverses the collection, but it can be solved by using the iterator's own deletion method.
  • Using the for loop to traverse and delete elements does not have this problem.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ListDemo4 {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("Java");
        list.add("java");
        list.add("java");
        list.add("MySQL");
        list.add("MySql");
        System.out.println(list);//[Java, java, MySQL, MySql]

        //Requirement: delete all Java information
        //1. Iterator traversal delete
//        Iterator<String> it = list.iterator();
//        while(it.hasNext()){
//            String ele = it.next();
//            if("java".equals(ele)){
//                list.remove("java"); / / (there will be bugs) error ConcurrentModificationException
                it.remove();//Use the iterator to delete the element at the current position, ensure that the index does not move back, and successfully delete all java and traverse all elements
//            }
//        }

        //2. foreach traversal deletion (there will be a bug)
//        for (String s : list) {
//            if("java".equals(s)){
//                list.remove("java"); / / an error is reported: ConcurrentModificationException
//            }
//        }

        //3. lambda traversal deletion (there will be a bug)
//        list.forEach(s -> {
//            if("java".equals(s)){
//                list.remove("java"); / / an error is reported: ConcurrentModificationException
//            }
//        });

        //4. for circular deletion does not report an error, but deleting from front to back will miss deleting elements
//        for (int i = 0; i < list.size(); i++) {
//            String ele = list.get(i);
//            if("java".equals(ele)){
//                list.remove("java");
//            }
//        }
//        System.out.println(list);//[Java, java, MySQL, MySql]

        //Solution: delete from back to front
//        for (int i = list.size()-1; i >=0; i--) {
//            String ele = list.get(i);
//            if("java".equals(ele)){
//                list.remove("java");
//            }
//        }
//        System.out.println(list);//[Java, MySQL, MySql]

        //Solution 2
        for (int i = 0; i < list.size(); i++) {
            String ele = list.get(i);
            if("java".equals(ele)){
                list.remove("java");
                i--;
            }
        }
        System.out.println(list);//[Java, MySQL, MySql]

    }
}

Posted by prosolutions on Sun, 05 Dec 2021 15:34:22 -0800