About collections and iterators

Keywords: Java Back-end

About containers (Collection)

1. What is a container

      Container is used to hold and manage objects. In life, we will use all kinds of containers. Such as pots and pans, boxes and bags. The "container" in the program also has similar functions to hold and manage data.

2. Structure of container

A single instance set is a single value, and a double instance set is a Key - Value

The Collection interface inherits the Iterator interface, implements the Iterator() method, and returns an Iterator object (write this first)

         This is the relationship between interface inheritance and implementation classes. It can be seen that the singleton container is basically the same. Because they are inherited from the Collection interface, the method implementation classes in the interface will be implemented. The difference is that other methods are customized during inheritance and implementation.

3. Abstract methods in collection

methodexplain
boolean add(Object element)
Add element to container
boolean remove(Object element)
Delete element from container
boolean contains(Object element)
Determine whether the element element is included
int size()
The number of elements in the container
boolean isEmpty()
Determine whether the container is empty
void clear()
Empty container
Iterator iterator()
Get iterator object
boolean containsAll(Collection c)
Determine whether this container contains all elements in container c
boolean addAll(Collection c)
Add all elements in container c to this container (repeatable)
boolean removeAll(Collection c)
Remove the elements contained in this container and container c
boolean retainAll(Collection c)
Take the elements contained in this container and container c, and remove the non intersecting elements
Object[] toArray()
Convert to Object array

After JDK8, a new method is added to the Collection interface

methodexplain
removeIf
The function is to delete all elements in the container that meet the conditions specified by the filter
stream
parallelStream
Stream and parallelStream return the stream view of the container respectively
The difference is that parallelStream() returns a parallel Stream,
Stream is the core class of Java functional programming.
spliterator

The separable iterator, unlike the previous iterator, requires sequential iteration. The splitter can be divided into several small iterators for parallel operation, which can realize multi-threaded operation and improve efficiency

4.List interface

          Order: order (the order in which elements are stored in the set is consistent with the order in which they are taken out). Each element in the List has an index tag. You can access elements based on their index tags (their positions in the List) to control them precisely.

         Repeatable: List allows you to add duplicate elements. More specifically, List usually allows elements that meet e1.equals(e2) to be added to the container repeatedly.

Common methods of List
methodexplain
void add (int index, Object element)
Inserts an element at the specified position, and all previous elements are moved back one bit
Object set (int index,Object element)        
Modify the element at the specified location
Object get (int index)
Returns the element at the specified location
Object remove (int index)
Delete the element at the specified position and move all subsequent elements forward one bit
int indexOf (Object o)
Returns the index of the first matching element, or - 1 if there is no such element
int lastIndexOf (Object o)
Returns the index of the last matching element, or - 1 if there is no such element

5.Array container class

ArrayList is the implementation class of the List interface. This is the concrete implementation of the List storage feature. The bottom layer of ArrayList is the storage implemented by array. Features: high query efficiency, low addition and deletion efficiency, unsafe thread.

Methods will not be described in detail. The use of specific methods is put in the following code. There are tests. If there is no test, it is not commonly used or not learned.

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

public class ArrayListTest {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();

        // Implement the two add methods in ArrayList
        boolean flag = list.add("edg");// This method is the method add(String a) in the collection interface. The return value is Boolean
        list.add("fpx");
        list.add(1, "rng");//This method is an abstract method defined by the sub interface list interface
        //void has no return value add(int index, String element)
        // The inserted index cannot be greater than the number of elements
        // Greater than the error IndexOutOfBoundsException

        //Implement the get method in ArrayList to obtain the element and length
        String s = list.get(0);
        System.out.println(s);
        //IndexOutOfBoundsException - if the index is out of range (index < 0 | index > = size())
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));
        }
        //Implement the set method in ArrayList to modify the element at the specified position
        list.set(0, "tes");
        System.out.println(list.get(0));
        //Implement the remove method in ArrayList to delete elements
        //Deleting an element according to its position returns the value of the deleted element, and the subscript of the following element moves forward
        String remove = list.remove(0);
        System.out.println(remove);
        //Delete the specified element (type is Object). The return value is Boolean success True failure False
        boolean fpx = list.remove("fpx");
        System.out.println(fpx); // true
        //Empty container clear
        list.clear();
        // Determine whether the container is empty isEmpty
        boolean empty = list.isEmpty();
        System.out.println(empty);//true
        //Determines whether the container contains the specified element contains
        list.add("ig");
        list.add("ug");
        list.add("ug");
        list.add("tg");
        boolean ig = list.contains("ig");
        System.out.println(ig);// true
        //The location of the lookup element does not exist. Return - 1
        list.indexOf("ug");// Returns the first occurrence of 1
        list.lastIndexOf("ug");// Returns the position where 2 last appeared
        //Convert singleton set to Object array
        //Cannot be forcibly converted to an array of type String [] because each array is of type Object
//        String[] array = (String[])list.toArray();
        Object[] array = list.toArray();
        for (int i = 0; i < array.length; i++) {
            String o = (String) array[i];
            System.out.println(o);
        }
        System.out.println("-----------------------------");
        //Singleton set conversion generic type array (common)
        String[] strings = list.toArray(new String[list.size()]);
        for (int i = 0; i < strings.length; i++) {
            System.out.println(strings[i]);
        }
        //When the sets are merged, the addAll element can be repeated (1 + 1 = 2). Note: neither set can be empty
        ArrayList<String> list1 = new ArrayList<>();
        ArrayList<String> list2 = new ArrayList<>();
        list1.add("a");
        list1.add("b");
        list2.add("c");
        list2.add("b");
/*        list1.addAll(list2);
        for (String t :
                list1) {
            System.out.println(t); // a b c b
        }*/
        //Set intersection retainAll
/*        list1.retainAll(list2);
        for (String t :
                list1) {
            System.out.println(t);// b
        }*/
        //The elements contained in list2 in the set difference set list.removeAll(list2) list will be removed
        list1.removeAll(list2);
        for (String t :
                list1) {
            System.out.println(t);// a
        }
    }
}

6.Stack container (stack)

         Stack stack container is a subclass of Vector, which implements a standard last in first out (LIFO: Last In Frist Out) stack.

public class StackTest {
    public static void main(String[] args) {
        // Instantiate object
        Stack<String> stack = new Stack<>();

        // Add element to stack
        String edg = stack.push("edg");
        System.out.println(edg);
        stack.push("rng");

        //Take element (pop stack)
        String pop = stack.pop();
        System.out.println(pop); // rng last in first out

        // Determine whether the stack container is empty
        boolean empty = stack.empty();
        System.out.println(empty);

        //View stack top element
        String peek = stack.peek();
        System.out.println(peek);

        //Returns the position of the element in the stack
        int edg1 = stack.search("edg");
        System.out.println(edg1); // 1. The initial position of finding elements in the stack container is from the top of the stack, and the maximum position is at the bottom of the stack

        // Judge the symmetry of elements
        StackTest stackTest = new StackTest();
        stackTest.FuHao();
    }
    public void FuHao(){
        String s = "...{.....[....(....)...]....}..(....)..[...]...";
        Stack<String> stack1 = new Stack<>();
        boolean flag = true;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c == '{'){
                stack1.push("}");
            }
            if (c == '['){
                stack1.push("]");
            }
            if (c == '('){
                stack1.push(")");
            }
            // Judge symbol matching
            if (c == ')' | c == ']' | c == '}'){
                if (stack1.empty()){
                    flag = false;
                    break;
                }
                char c1 = stack1.pop().charAt(0);
                if (c1 != c){
                    flag = false;
                    break;
                }
            }
        }
        if(!stack1.empty()){
            flag = false;
        }
        System.out.println(flag);
    }
}

7.Set interface

Set features: disordered and unrepeatable.

Unordered means that the elements in the Set have no index, so we can only traverse and find;

Non repeatable means that duplicate elements are not allowed. More specifically, if the new element is true compared with an element in the Set through the equals() method, only one element can be retained. The commonly used implementation classes of Set include HashSet, TreeSet, etc. we generally use HashSet.

It's similar to List, so I didn't write the code. I also read Map a little and understood the single case set and double case set. Just like mathematics, I first figured out the low-dimensional (linear, plane) and then extended it to the high-dimensional. I'll add it later this semester... Time tension ==

Iterator

1. Introduction to iterator iterator interface

                 The Collection interface inherits the Iterable interface, which contains an abstract method named Iterator. All container classes that implement the Collection interface implement this method. The Iterator method will return an Iterator object of Iterator interface type, which contains three methods to implement the iterative processing of the singleton container.

methodexplain
boolean hasNext()

Judge whether there are elements in the current position of the cursor. If so, return true; otherwise, return false

Object next()

Gets the element where the current cursor is located and moves the cursor to the next position

void remove()

Delete the element at the current position of the cursor. This operation can only be performed once after executing next

Iterator code test (the iterator is universal, so there is no difference between the two interface tests)

Code testing based on List interface

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

public class IteratorListTest {
    public static void main(String[] args) {
        //Testing iterators with ArrayList
        // Instantiate object
        List<String> list = new ArrayList<>();
        list.add("edg");
        list.add("rng");
        list.add("lng");
        //The Iterator object was created because the Collection interface inherits the Iterator interface
        // Where the Iterator method returns an Iterator object
        Iterator<String> iterator =list.iterator();
        //while loop
        while (iterator.hasNext()){
            String value = iterator.next();
            System.out.println(value);
        }
        // for loop
        // Note: here, the first sentence of the for loop retrieves an iterator
        // Because the iterator can only be used once, the while loop above has run out, and the iterator has come to an end
        // It is useless to use iterator.hasNext() in the for loop; If it's false, it stops
        //for(;iterator.hasNext();) / / the writing method of not creating a new iterator. Note that there are two semicolons
        for(Iterator<String> iterator1 = list.iterator();iterator1.hasNext();){
             String value = iterator1.next();
            System.out.println(value);
        }
    }
}

Test based on Set interface code

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class IteratorSetTest {
    public static void main(String[] args) {
        //Testing iterators with HashSet
        // Instantiate object
        Set<String> set = new HashSet<>();
        set.add("edg");
        set.add("rng");
        set.add("lng");
        //The Iterator object was created because the Collection interface inherits the Iterator interface
        // Where the Iterator method returns an Iterator object
        Iterator<String> iterator =set.iterator();
        //while loop
        while (iterator.hasNext()){
            String value = iterator.next();
            System.out.println(value);
        }
        // for loop
        for(Iterator<String> iterator1 = set.iterator();iterator1.hasNext();){
            String value = iterator1.next();
            System.out.println(value);
        }
    }
}

Delete element in iterator

remove() method, just understand it. Try not to add or delete elements during iteration or for traversal!!!

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

// Try not to use this method to delete elements with iterators
public class IteratorRemoveTest {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("a");
        list.add("b");
        list.add("c");
        list.add("d");
        Iterator<String> it = list.iterator();//This sentence should be placed after add, otherwise the created iterator is empty
        for(; it.hasNext();){
            if("c".equals(it.next())){
                it.remove();
            }
        }
        System.out.println(list);
    }
}

Collections tool class

         Collections is a tool class that provides auxiliary methods for sorting, filling and finding elements of Set, List and Map. All methods in this class are static. (can be called directly with class)

methodexplain
void sort(list)
Sort the elements in the List container in ascending order
void shuffle(List)
Randomly arrange the elements in the List container. (shuffle)
void reverse(List)
/Inversely arrange the elements in the List container
void fill(List, Object)
Rewrite the entire List container with a specific object.
int binarySearch(List, Object)
For sequential List containers, use the half search method
Specific objects.
import java.util.ArrayList;
import java.util.Collections;

//For example, implement the sort method (sorting from small to large) in the Collections tool class
public class CollectionsSortTest {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.add("a");
        list.add("b");
        list.add("e");
        list.add("d");
        list.add("c");
        System.out.println(list);//[a, b, e, d, c]
        Collections.sort(list);
        System.out.println(list);//[a, b, c, d, e]
    }
}

I only tested the Sort method here. The sorting rules here are in the system. Of course, you can customize the rules yourself. At present, they are arranged as a,b,c... And you can customize them as b at the minimum (top). This requires some comparison methods in the Comparator interface. The comparison rules are written by yourself, and then the rules defined by Sort1 can be passed into Sort. (I won't write this. I'll come back later and add a Sort rule)

class Sort1 implements Comparator<String>{

    @Override
    public int compare(String o1, String o2) {
        return 0;
    }
}

If you are interested in other methods, test them yourself~

Posted by Houdini on Wed, 17 Nov 2021 04:55:37 -0800