Java learning notes: container

Keywords: Java Container IDEA

container

A Collection, also known as a Collection, is used to hold and manage data.

1. Singleton set

1.1 concept

Singleton set: store data one by one.

Collection interface: it is the root interface of a singleton collection and has two sub interfaces. It is divided into List interface (orderly storage, repeatable, "dynamic" array) and Set interface (disordered storage, non repeatable, "Set" in Mathematics)

List interface: ArrayList class, LinkedList class, Vector class

Set interface: LinkedHashSet class, HashSet class, TreeSet class

1.2 abstract methods in collection interface

methodexplain
boolean add(Object element)Add element to container
boolean remove(Object element)Remove element from container
boolean contains(Object element)Does the container contain this element
int size()The number of elements in the container
boolean isEmpty()Is the container empty
void clear()Empty all elements in the container
Iterator iterator()Gets an iterator that traverses all elements
boolean containsAll(Collection c)Does this container contain all the elements in the c container
boolean addAll(Collection c)Add all elements in container c to this container
boolean removeAll(Collection c)Remove the elements contained in both 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

1.3 List interface

characteristic:

  • Order: the order in which elements are stored in the collection is consistent with the order in which they are taken out. Each element in the List has an index mark. You can access elements according to the index mark of elements, so as to accurately control these elements
  • 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:

In addition to the methods in the Collection interface, List has some more methods related to order (index)

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

1.3.1 ArrayList container class

ArrayList is the implementation class of the List interface and the specific 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 and unsafe thread

Basic implementation:

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

public class ArrayListTest {
    public static void main(String[] args) {
        List<String > list = new ArrayList<>();  //Instantiate the ArrayList container
        list.add("abab");   //Add element
        list.add("cdcd");
        list.add("efef");
        list.add(1,"waiter");  //The specified position cannot be greater than the number of elements

        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));     //Get element
        }
        System.out.println("list Number of elements:"+list.size());  //Number of elements

        //Delete element
        String value = list.remove(1);  //Delete the element according to the index position and return the deleted element
        System.out.println(value);
        boolean flag = list.remove("haha");  //If the specified element is deleted, true will be returned if successful, and false if the specified element is not found
        System.out.println(flag);

        String value2 = list.set(1, "haha");//Replace the element and return the replaced element
        System.out.println(value2);

        System.out.println("list Does the container contain abab Element:"+list.contains("abab"));  //Judge whether the container contains the element. If yes, it returns true; otherwise, it returns false

        System.out.println(list.indexOf("haha"));  //The indexOf method returns the position where the element first appears in the container. If it does not exist, it returns - 1
        System.out.println(list.lastIndexOf("haha"));  //The lastIndexOf method returns the position of the last occurrence of the element in the container. If it does not exist, it returns - 1

        Object[] arr = list.toArray();  //The ArrayList is converted to an Object array. The converted array cannot be cast
        for (int i = 0; i < arr.length; i++) {
            String str = (String) arr[i];
            System.out.println(str);
        }
        String[] arr2 = list.toArray(new String[list.size()]);  //Converts a singleton collection to an array of the specified type
        for (int i = 0; i < arr2.length; i++) {                 //The singleton collection can be converted to an array of specified types, but the type needs to refer to the type in the generic type
            System.out.println(arr2[i]);
        }

        list.clear();     //Empty container
        System.out.println("Number of containers:"+list.size());   //0
        System.out.println("Whether the container is empty:"+list.isEmpty());  //Judge whether the container is empty, return true if it is empty, and false if it is not empty


        List<String> a = new ArrayList<>();
        a.add("a");
        a.add("b");
        a.add("c");
        List<String> b = new ArrayList<>();
        b.add("c");
        b.add("d");
        b.add("e");
        System.out.println(a.addAll(b));  //Union operation of containers, a and b
        for (String str: a) {
            System.out.println(str);   //a b c c d e
        }

        List<String> a1 = new ArrayList<>();
        a1.add("a");
        a1.add("b");
        a1.add("c");
        List<String> b1 = new ArrayList<>();
        b1.add("c");
        b1.add("d");
        b1.add("e");
        System.out.println(a1.retainAll(b1));  //Intersection operation of containers, a and b
        for (String str: a1) {
            System.out.println(str);   //c
        }

        List<String> a2 = new ArrayList<>();
        a2.add("a");
        a2.add("b");
        a2.add("c");
        List<String> b2 = new ArrayList<>();
        b2.add("c");
        b2.add("d");
        b2.add("e");
        System.out.println(a2.retainAll(b2));  //Difference set operation of container, a-b
        for (String str: a2) {
            System.out.println(str);   //a b
        }
    }
}

1.3.2 Vector container

The underlying layer of Vector is implemented by array, and the related methods are added with synchronization check, so * * "thread safety, low efficiency" * *. For example, the indexOf method adds the synchronized synchronization flag.

The use of Vector is the same as that of ArrayList, because they both implement the List interface and implement the abstract methods in the List interface.

The difference between Vector and ArrayList is that Vector multithreading is safe, while ArrayList multithreading is not safe.

Simple implementation:

public class VectorTest {
    public static void main(String[] args) {
        List<String> v = new Vector<>();
        v.add("aaa");     //Add element
        v.add("bbb");
        v.add("ccc");
        for (int i = 0; i < v.size(); i++) {
            System.out.println(v.get(i));          //Get element
        }
    }
}

Stack container:

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

Features: last in, first out. The Vector is extended through five operation methods, allowing the Vector to be regarded as a stack.

Simple implementation:

public class StackTest {
    public static void main(String[] args) {
        Stack<String> stack = new Stack<>();
        stack.push("aaa");     //Element stack
        stack.push("bbb");
        stack.push("ccc");
        System.out.println(stack.size());   //Number of elements in stack
        System.out.println(stack.pop());    //Element bomb stack
        System.out.println(stack.empty());  //Judge whether the stack is empty. If yes, return true; otherwise, return false
        System.out.println(stack.peek());   //View stack top element
        System.out.println(stack.search("aaa"));  //Returns the position of the element in the stack container. The stack element position starts from 1 and starts from the top of the stack
    }
}

Bracket matching problem:

public class StackTest02 {
    public void symmetry(){
        String str = "{...[..(..)..]...}.(..)..[..]..{..}";
        Stack<String> stack = new Stack<>();
        boolean flag = true;
        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            if (ch == '('){               //If it is an open bracket, press the stack
                stack.push(")");
            }
            if (ch == '['){
                stack.push("]");
            }
            if (ch == '{'){
                stack.push("}");
            }
            if (ch == ')'||ch == ']'||ch == '}'){   //If it is the right bracket, it will pop up the stack
                if (stack.empty()){
                    flag = false;
                    break;
                }
                String topStr = stack.pop();
                if (topStr.charAt(0) != ch){
                    flag = false;
                    break;
                }
            }
        }
        if (!stack.empty()){
            flag = false;
        }
        if (flag){
            System.out.println("Match succeeded!");
        }else {
            System.out.println("Matching failed!");
        }
    }

    public static void main(String[] args) {
        StackTest02 stack = new StackTest02();
        stack.symmetry();
    }
}

1.3.3 LinkedList container class

The underlying LinkedList uses a bidirectional linked list to store.

**Features: * * low query efficiency, high addition and deletion efficiency and unsafe thread

Use of LinkedList (List standard):

LinkedList implements the List interface. Using LinkedList has the storage characteristics of List (ordered and repeatable elements).

        List<String > list = new LinkedList<>();
        list.add("aaa");     //Add element
        list.add("bbb");
        list.add("ccc");
        list.add("aaa");
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));         //Get element
        }

Use of LinkedList (non List standard):

public class LinkedListTest02 {
    public static void main(String[] args) {
        LinkedList<String> linkedList = new LinkedList<>();
        linkedList.addFirst("aaa");          //Inserts the specified element at the beginning
        linkedList.addLast("bbb");           //Inserts the specified element to the end
        linkedList.addFirst("ccc");
        for (String str:linkedList) {
            System.out.println(str);        //ccc aaa bbb
        }
        System.out.println(linkedList.getFirst());    //Returns the first element of this linked list
        System.out.println(linkedList.getLast());     //Returns the last element of this linked list
        linkedList.removeFirst();          //Remove the first element in this linked list and return this element
        linkedList.removeLast();           //Remove the last element in this linked list and return this element
        linkedList.pop();                  //An element pops up from the stack represented by the linked list, which is equivalent to removeFirst
        linkedList.push("ddd");         //Pushing elements into the stack represented by this linked list is equivalent to addfirst (E)
        System.out.println(linkedList.isEmpty());  //Judge whether the linked list is empty. If yes, return true; otherwise, return false
    }
}

1.4 Set interface

The Set interface inherits from the Collection interface. There is no new method in the Set interface, and the method is completely consistent with the Collection.

characteristic:

  • Unordered: the elements in the Set have no index and can only be searched by traversal
  • Non repeatable: duplicate elements are not allowed to be added. If a new element is compared with an element in the Set through the equals() method to true, only one can be retained.

The commonly used implementation classes of Set include HashSet, TreeSet, etc

1.4.1 HashSet container class

HashSet is implemented by hash algorithm, and the bottom layer is actually implemented by HashMap (HashSet is essentially a simplified version of HashMap), so the query efficiency and addition and deletion efficiency are relatively high.

Basic implementation:

public class HashSetTest {
    public static void main(String[] args) {
        Set<String> set = new HashSet<>();
        set.add("aaa");             //Add element
        set.add("bbb");
        set.add("ccc");
        set.add("aaa");   //There can be no duplicate elements, so there are only aaa bbb ccc and no two aaa in the Set container at this time
        //Get the element. There is no index in the Set container, so there is no corresponding get(int index) method
        for (String str:set) {        //You can get elements through a foreach loop
            System.out.println(str);
        }
        System.out.println(set.remove("aaa"));  //When deleting an element, true is returned for success, and false is returned for failure
        System.out.println(set.size());            //Returns the number of elements
    }
}

HashSet storage feature analysis:

HashSet is a collection without duplicate elements and does not guarantee the order of elements. It is thread unsafe. Moreover, HashSet allows null elements.

Unordered: in the HashSet, the underlying element is stored using HashMap. The underlying HashMap uses arrays and linked lists to store elements. When elements are stored in an array, they are not stored orderly or randomly, but the hash value of the elements is calculated to determine the position of the elements in the array.

No repetition: when the hash values of two elements are calculated to obtain the same position in the array, the equals() method of the element will be called to judge whether the two elements are the same. If the elements are the same, no element will be added. If they are different, the element will be saved using a one-way linked list.

Store custom objects through HashSet:

If you want to implement non repeating elements in a custom object, you need to override the equals() method and hashCode() method in the custom object.

Users object:

public class Users {
    private String username;
    private int userage;

    public Users(String username, int userage) {
        this.username = username;
        this.userage = userage;
    }
    public Users(){}

    @Override
    public String toString() {
        return "Users{" +
                "username='" + username + '\'' +
                ", userage=" + userage +
                '}';
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public int getUserage() {
        return userage;
    }

    public void setUserage(int userage) {
        this.userage = userage;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Users users = (Users) o;
        return userage == users.userage && Objects.equals(username, users.username);
    }

    @Override
    public int hashCode() {
        return Objects.hash(username, userage);
    }
}

Test class:

public class HashSetTest02 {
    public static void main(String[] args) {
        Set<Users> set = new HashSet<>();
        Users u1 = new Users("xxx",18);
        Users u2 = new Users("xxx",18);
        set.add(u1);
        set.add(u2);
        System.out.println(u1.hashCode());
        System.out.println(u2.hashCode());
        for (Users user :
                set) {
            System.out.println(user);
        }
    }
}

1.4.2 TreeSet container class

TreeSet is a container that can sort elements. The bottom layer is actually implemented by TreeMap. A simplified version of TreeMap is maintained internally, and the elements of Set are stored by key. The stored elements need to be sorted internally in TreeSet, so a sorting rule needs to be given.

Implementation method of sorting rule: the comparison rule is implemented through the element itself, and the comparison rule is specified through the comparator.

Basic implementation:

public class TreeSetTest {
    public static void main(String[] args) {
        Set<String> set = new TreeSet<>();
        set.add("aaa");   //Add element
        set.add("ddd");
        set.add("bbb");
        set.add("ccc");
        set.add("aaa");
        for (String str :
                set) {
            System.out.println(str);   //Traverse the TreeSet container, aaa bbb ccc ddd, and sort the elements inside the TreeSet
        }
    }
}

Implement comparison rules through the element itself:

The compareTo method in the Comparable interface needs to be implemented, which is used to define comparison rules. TreeSet calls this method to complete the sorting of elements.

User class:

public class Users implements Comparable<Users>{
    private String username;
    private int userage;

    public Users(String username, int userage) {
        this.username = username;
        this.userage = userage;
    }
    public Users(){}

    @Override
    public String toString() {
        return "Users{" +
                "username='" + username + '\'' +
                ", userage=" + userage +
                '}';
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public int getUserage() {
        return userage;
    }

    public void setUserage(int userage) {
        this.userage = userage;
    }

    @Override
    public int compareTo(Users o) {         //The compareTo method is implemented. The primary keyword is age and the secondary keyword is name (dictionary order)
        if (this.userage > o.getUserage()){
            return 1;
        }
        if (this.userage == o.getUserage()){
            return this.username.compareTo(o.getUsername());
        }
        return -1;
    }
}

Implementation class:

public class TreeSetTest02 {
    public static void main(String[] args) {
        Set<Users> set = new TreeSet<>();
        Users u1 = new Users("xxx",18);
        Users u2 = new Users("yyy",10);
        Users u3 = new Users("aaa",10);
        set.add(u1);
        set.add(u2);
        set.add(u3);
        for (Users user :
                set) {
            System.out.println(user);
        }
    }
}

Comparison rules are implemented through Comparators:

A Comparator needs to be created separately. The Comparator needs to implement the compare method in the Comparator interface to define the comparison rules. When instantiating TreeSet, the Comparator object is handed over to TreeSet to complete the sorting of elements. At this time, the element itself does not need to implement the comparison rules.

Create comparator:

public class StudentComparator implements Comparator<Students> {
    @Override
    public int compare(Students o1, Students o2) {   //Define comparison rules
        if (o1.getAge() > o2.getAge()){
            return 1;
        }
        if (o1.getAge() == o2.getAge()){
            return o1.getName().compareTo(o2.getName());
        }
        return -1;
    }
}

Students class:

public class Students {
    private String name;
    private int age;

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

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Students students = (Students) o;
        return age == students.age && Objects.equals(name, students.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }

    @Override
    public String toString() {
        return "Students{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

Test class:

public class TreeSetTest03 {
    public static void main(String[] args) {
        Set<Students> set = new TreeSet<>(new StudentComparator());
        Students s1 = new Students("xxx",18);
        Students s2 = new Students("yyy",20);
        Students s3 = new Students("xyz",20);
        set.add(s1);
        set.add(s2);
        set.add(s3);
        for (Students stu :
                set) {
            System.out.println(stu);
        }
    }
}

1.5 single case set use cases

Generate the closed interval of random number [1,10] () between 1-10, and put the non repeated 10 random numbers into the container.

List type container implementation:

public class TestList {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();
        while (true){
            int num = (int)(Math.random() * 10 + 1);  //Get random number
            if (!list.contains(num)){                //Judge whether the random number already exists in the list
                list.add(num);
            }
            if (list.size() == 10){
                break;
            }
        }
        for (Integer i :
                list) {
            System.out.println(i);
        }
    }
}

Set type container implementation:

public class TestSet {
    public static void main(String[] args) {
        Set<Integer> set = new HashSet<>();
        while (true){
            int num = (int)(Math.random() * 10 + 1);
            set.add(num);   //Since the Set type container does not allow duplicate elements, there is no need to judge
            if (set.size() == 10){
                break;
            }
        }
        for (Integer i :
                set) {
            System.out.println(i);
        }
    }
}

2. Double case set

Double instance set: stores data based on Key and Value structures. Function y=f(x) in Mathematics

Map interface: HashTable class, HashMap class, TreeMap class, LinkedHashMap class, Properties class

2.1 introduction to map interface

The Map interface defines the storage characteristics of the double instance Collection. It is not a sub interface of the Collection interface. The storage feature of double instance set is that it is stored in key and value structures.

Difference between Map and Collection:

  • The container elements in the Collection exist in isolation. The elements stored in the Collection are stored one by one
  • The container elements in the Map exist in pairs. Each element consists of a key and a value. The corresponding value can be found through the key.
  • Containers in the Collection are called singleton collections, and containers in the Map are called Double instance collections.
  • The collection in the Map cannot contain duplicate keys, and the values can be repeated. Each key can only correspond to one value.
  • The commonly used containers in Map are HashMap, TreeMap, etc.

Common methods of Map:

methodexplain
V put(K key,V value)Add key and value to the Map collection
void putAll(Map m)Copy all mapping relationships from the specified Map to this Map
V get(Object key)Obtain the corresponding value according to the specified key
boolean containsKey(Object key)Judge whether the container contains the specified key
boolean containsValue(Object value)Determines whether the container contains the specified value
Set keySet()Get all the key s in the Map collection and store them in the Set collection
Set<Map.Entry<K,V>> entrySet()Returns a Set that contains all the mappings in the Map based on the Map.Entry type
void clear()Delete all mappings in the Map

2.2 HashMap container class

HashMap is the interface implementation class of Map interface. It is implemented by hash algorithm. It is the most commonly used implementation class of Map interface. Because the underlying layer uses a hash table to store data, it is required that the key cannot be repeated. In case of repetition, the new value will replace the old value. HashMap has very high efficiency in finding, deleting and modifying.

Basic operation:

public class TestHashMap {
   public static void main(String[] args) {
       Map<String ,String > map1 = new HashMap<>();
       map1.put("a","A");      //Add element
       map1.put("b","B");
       map1.put("c","C");
       map1.put("d","D");

       System.out.println(map1.get("a"));    //Get element
       Set<String> keys = map1.keySet();     //To obtain all elements in the HashMap container, you can use the keySet method and the get method together
       for (String key :
               keys) {
           String value = map1.get(key);
           System.out.println(key + " --- " + value);
       }
       Set<Map.Entry<String,String>> entrySet = map1.entrySet();   //Get Map.Entry elements through entrySet
       for (Map.Entry<String, String> entry :
               entrySet) {
           String key = entry.getKey();          //Get Key
           String value = entry.getValue();      //Get Value
           System.out.println(key + "---"+ value);
       }

       System.out.println("-------------------------");
       Map<String,String> map2 = new HashMap<>();
       map2.put("f","F");
       map2.put("c","CCC");     //Because map1 and map2 have the same key, the merged container map1 will overwrite the value with the same key in the current container map2
       map2.putAll(map1);        //Union operation to merge all elements in map1 into map2
       Set<String> keys2 = map2.keySet();
       for (String key2 :
               keys2) {
           System.out.println(key2 + " --- " + map2.get(key2));
       }

       String value = map1.remove("b");    //Delete the element and return the deleted element
       System.out.println(value);
       Set<String> keys3 = map1.keySet();
       for (String key3 :
               keys3) {
           System.out.println(key3 + " = " + map1.get(key3));
       }

       //Judge whether the key or value exists. If it exists, return true; otherwise, return false
       System.out.println(map1.containsKey("aaa"));   //Judge key, false
       System.out.println(map1.containsKey("a"));   //Judge key, true
       System.out.println(map1.containsValue("A")); //Judge value, true
   }
}

HashMap underlying storage:

The underlying implementation of HashMap adopts hash table. The essence of hash table is "array + linked list".

If the number of nodes in the linked list in the hash table is greater than 8, it will be automatically converted to a red black tree. When the number of nodes is less than 6, it is converted to a linked list.

2.3 TreeMap container class

TreeMap and HashMap also implement the Map interface, so there is no difference in the usage of API. HashMap is more efficient than TreeMap.

TreeMap can sort keys.

The bottom layer of TreeMap is based on red black tree.

When using TreeMap, you need to give a sorting rule: the element itself implements the comparison rule, and the comparison rule is implemented through the comparator.

Implement comparison rules through the element itself:

//Users class
public class Users implements Comparable<Users>{
    private String username;
    private int userage;

    public Users(String username, int userage) {
        this.username = username;
        this.userage = userage;
    }
    public Users(){}

    @Override
    public String toString() {
        return "Users{" +
                "username='" + username + '\'' +
                ", userage=" + userage +
                '}';
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public int getUserage() {
        return userage;
    }

    public void setUserage(int userage) {
        this.userage = userage;
    }

    @Override
    public int compareTo(Users o) {
        if (this.userage < o.getUserage()){
            return 1;
        }
        if (this.userage == o.getUserage()){
            return this.username.compareTo(o.getUsername());
        }
        return -1;
    }
}
//Test class
public class TestTreeMap {
    public static void main(String[] args) {
        Map<Users,String> map = new TreeMap<>();
        Users u1 = new Users("xxx",18);
        Users u2 = new Users("yyy",20);
        map.put(u1,"xxx");
        map.put(u2,"yyy");
        Set<Users> keys = map.keySet();
        for (Users key :
                keys) {
            System.out.println(key+" --- "+map.get(key));
        }
    }
}

Comparison rules are implemented through Comparators:

//Students class
public class Students {
    private String name;
    private int age;

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

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Students students = (Students) o;
        return age == students.age && Objects.equals(name, students.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }

    @Override
    public String toString() {
        return "Students{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}
//Create comparison rule
public class StudentComparator implements Comparator<Students> {
    @Override
    public int compare(Students o1, Students o2) {   //Define comparison rules
        if (o1.getAge() > o2.getAge()){
            return 1;
        }
        if (o1.getAge() == o2.getAge()){
            return o1.getName().compareTo(o2.getName());
        }
        return -1;
    }
}
//Test class
public class TestTreeMap {
    public static void main(String[] args) {
        Map<Students,String> treeMap = new TreeMap<>(new StudentComparator());
        Students stu1 = new Students("xxx",18);
        Students stu2 = new Students("yyy",22);
        Students stu3 = new Students("zzz",20);
        treeMap.put(stu1,"xxx");
        treeMap.put(stu2,"yyy");
        treeMap.put(stu3,"zzz");

        Set<Students> keys = treeMap.keySet();
        for (Students key :
                keys) {
            System.out.println(key + " --- " + treeMap.get(key));
        }
    }
}

3. Iterator iterator

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 interface defines the following methods:

  • 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

Iterate List interface type container

public class testIterator {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("aaa");
        list.add("bbb");
        list.add("ccc");
        Iterator<String> iterator = list.iterator();
        //In the iterator, the element is obtained through the while loop
        while (iterator.hasNext()){
            String value = iterator.next();
            System.out.println(value);
        }
        //In the iterator, get the element through the for loop
        for (Iterator<String> iterator1 = list.iterator();iterator1.hasNext();){
            String value = iterator1.next();
            System.out.println(value);
        }
    }
}

Iteration Set interface type container

public class testIterator02 {
    public static void main(String[] args) {
        Set<String> set = new HashSet<>();
        set.add("aaa");
        set.add("bbb");
        set.add("ccc");
        //while
        Iterator<String> iterator = set.iterator();
        while (iterator.hasNext()){
            String value = iterator.next();
            System.out.println(value);
        }
        //for
        for (Iterator<String> iterator1 = set.iterator();iterator1.hasNext();){
            String value = iterator1.next();
            System.out.println(value);
        }
    }
}

Delete element in iterator

Adding elements is not allowed when iterating over iterators or for each loops (the underlying is also implemented using iterators).

public class testIteratorRemove {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("a");
        list.add("b");
        list.add("c");
        list.add("d");
        //Delete elements through the for loop
        for (int i = 0; i < list.size(); i++) {
            if ("c".equals(list.get(i))){
                list.remove(i);
            }
            System.out.println(list.get(i));
        }

        //Delete elements through iterators
        Iterator<String> iterator = list.iterator();
        while (iterator.hasNext()){
            String value = iterator.next();
            if ("b".equals(value)){
                iterator.remove();
            }
        }
        for (Iterator<String> iterator1 = list.iterator();iterator1.hasNext();){
            String value = iterator1.next();
            System.out.println(value);
        }
    }
}

4. Collections tool class

Collections is a tool class that provides auxiliary methods for sorting, filling and finding elements in Set, List and Map. All methods in this class are static.

Common methods:

  • void sort(List) / / sort the elements in the List container in ascending order
  • void shuffle(List) / / randomly arrange the elements in the List container
  • void reverse(List) / / arrange the elements in the List container in reverse order
  • void fill(List,Object) / / rewrite the entire List container with a specific object
  • int binarySearch(List,Object) / / for sequential List containers, use the split search method to find specific objects

Basic implementation:

public class testCollections {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("c");
        list.add("b");
        list.add("d");
        list.add("a");
        Collections.sort(list);         //Ascending order
        for (String str :
                list) {
            System.out.println(str);      //a b c d
        }
        Collections.shuffle(list);       //Random sorting (out of order)
        for (String str :
                list) {
            System.out.println(str);      //Each execution result is different
        }
    }
}

Posted by kabucek1 on Mon, 08 Nov 2021 16:13:12 -0800