The fifth week of java learning notes

Posted by bugz-2849 on Sat, 12 Feb 2022 19:58:10 +0100

Catalog

1. Containers (2) - Double Case Set

1. Introduction of Map interface

1.1 Map interface features

1.2 Common Map Methods

2. HashMap Container Class

2.1 Add Elements

2.2 get method to get elements

2.3 Union Operation

2.4 Delete elements

2.5 Determine whether key and value exist

3,TreeMap

3.1 Elements themselves implement comparison rules

3.2 Implementing comparison rules through a comparator

4. Iterator Iterator

4.1 Introduction to Iterator iterator interface

4.2 Iterator Iteration List Interface Type Container

4.3 Iterator Iteration Set Interface Type Container

4.3 Delete elements in iterators

5. Collections Tool Class

5.1 Sort LIst containers

5.2 Random sorting of List-type containers

1. Containers (2) - Double Case Set

1. Introduction of Map interface

1.1 Map interface features

1.2 Common Map Methods

2. HashMap Container Class

HashMap is the interface implementation class for the Map interface. It is implemented using a hash algorithm and is the most commonly used implementation class for the Map interface. Since the underlying hash table is used to store data, it is required that keys not be duplicated, and if duplication occurs, the new value replaces the old value. HashMap is very efficient in finding, deleting, and modifying.

2.1 Add Elements

The put method is characterized by encountering elements of the same Key, replacing the old Value with the new Value, and returning the old Value

package studyweek5 container;

import java.util.HashMap;
import java.util.Map;

public class HashMapTest {
    public static void main(String[] args) {
        //Instantiate HashMap Container
        //The put method is characterized by encountering elements of the same Key, replacing the old Value with the new Value, and returning the old Value
        Map<String,String> map=new HashMap();
        String value=map.put("a","A");
        System.out.println(value);//There was no Key in the original Map, so it returned empty

        String value2=map.put("a","B");
        System.out.println(value2);//B will

    }
}

2.2 get method to get elements

Method 1: Get the Value value from Key

        //1. Get Value from Key
        //If Key knows, the get method is convenient
        String value3=map.get("a");
        System.out.println(value3);

Disadvantages:

1. You must know all the Key values

2. The get method needs to be called several times to get all the Value s.

Method 2: Get elements by KeySet method

        //2. Get all the elements in the container through the KeySet method, which can be done using the KeySet method and the get method together.
        map.put("b","B");
        map.put("c","C");
        map.put("d","D");
        map.put("e","E");
        Set<String> keys= map.keySet();//Do not instantiate objects
        map.keySet();
        for(String key:keys){
            String v1=map.get(key);
            System.out.println(key+"-"+v1);
        }

Mode 3: Get a Map through the entrySet method. Entry Type Get Element

//3. Get Map through entrySet method. Entry type gets element (with internal interface Entry of Map interface)
        //Split a bunch of K-V pairs into a Set
        Set<Map.Entry<String,String>> entrySet=map.entrySet();
        for(Map.Entry<String,String> entry:entrySet){
            String key=entry.getKey();
            String v=entry.getValue();
            System.out.println(key+"---"+v);
        }

2.3 Union Operation

     //Union operation
        Map<String,String> map2=new HashMap<>();
        map2.put("f","F");
        map2.put("c","cc");//During union operation, if two maps have the same Key, the K-V in the map will be overwritten by the K-V of the copied Map.
        map2.putAll(map);
        Set<String> keys2=map2.keySet();
        for(String key:keys2){
            String v2=map2.get(key);
            System.out.println(key+"-"+v2);
        }

2.4 Delete elements

        //Delete element
        String v=map.remove("e");
        System.out.println(v);//Returns the deleted Value value
        Set<String> keys3=map.keySet();
        for(String key:keys3){
            System.out.println(key+"---"+map.get(key));
        }

2.5 Determine whether key and value exist

        //Determine whether key and value exist
        System.out.println(map.containsKey("a"));//Determine if key exists
        System.out.println(map.containsValue("BBB"));//Determine if value exists

3,TreeMap

TreeMap and HashMap also implement the Map interface, so there is no difference in API usage. HashMap is more efficient than TreeMap; TreeMap is a container for sorting keys. TreeMap can be used when sorting keys is required. The bottom layer of TreeMap is based on red and black trees.

Given collation is required when using TreeMap:

Element implements comparison rules by itself

Implement comparison rules through a comparator

3.1 Elements themselves implement comparison rules

//Override compareTo method in HashSetUser
@Override
    public int compareTo(HashSetUsers o) {
        if(this.userage>o.getUserage()){ //From large to small
            return 1;
        }
        if(this.userage==o.userage){
            return this.username.compareTo(o.getUsername());
        }
        return -1;
    }
package studyweek5 container;

import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

public class TreeMapTest {
    public static void main(String[] args) {
        //Instantiate TreeMap
        Map<HashSetUsers,String> map=new TreeMap<>();
        HashSetUsers u1=new HashSetUsers("Zhang San",18);
        HashSetUsers u2=new HashSetUsers("Li Si",20);
        HashSetUsers u3=new HashSetUsers("King Five",18);
        map.put(u1,"Zhang San");
        map.put(u2,"Li Si");
        map.put(u3,"King Five");
        Set<HashSetUsers> keys=map.keySet();
        for(HashSetUsers key:keys){
            System.out.println(key+"-------"+map.get(key));
        }

    }
}

3.2 Implementing comparison rules through a comparator

package studyweek5 container;

import java.util.Objects;

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

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

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

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

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

    public Student() {
    }

    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;
    }
}
      Map<Student,String> treeMap=new TreeMap<>(new StudentComparator());
        Student s1=new Student("Zhang San",18);
        Student s2=new Student("Li Si",20);
        Student s3=new Student("King Five",18);
        treeMap.put(s1,"Zhang San");
        treeMap.put(s2,"Li Si");
        treeMap.put(s3,"King Five");
        Set<Student> keys1=treeMap.keySet();
        for(Student key:keys1){
            System.out.println(key+"-------"+treeMap.get(key));
        }

4. Iterator Iterator

4.1 Introduction to Iterator iterator interface

The Collection interface inherits the Iterable interface, which contains an abstract method called iterator, which is implemented specifically by all container classes that implement the Collection interface. The iterator method returns an iterator object of the Iterator interface type that contains three methods for iterating over a single container. How the Iterator object works:

 

The Iterator interface defines the following methods:

booleanhasNext();// Determines if there is an element at the current cursor position, and if it returns true, otherwise it returns false. *

Objectnext();// Gets the element where the current cursor is located and moves the cursor to the next location;

voidremove();// Delete the element at the cursor's current position, which can only be performed once after next is executed;

4.2 Iterator Iteration List Interface Type Container

package studyweek5 container;

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

public class IteratorListTest {
    public static void main(String[] args) {
        //Instantiation Container
        List<String> list=new ArrayList<>();
        list.add("a");
        list.add("b");
        list.add("c");

        //Get elements (using iterators)
        //Get Iterator Object
        Iterator<String> iterator=list.iterator();
        /*boolean flag=iterator.hasNext();
        if(flag){
            String value=iterator.next();
            System.out.println(value);
        }*/  //iterator does not have a loop condition, so the above code can only get one element

        //Mode 1: Get elements through a while loop in an iterator
        while(iterator.hasNext()){
            String value=iterator.next();
            System.out.println(value);
        }
        //Mode 1: In an iterator, get elements through a for loop
        for(Iterator<String> it=list.iterator();it.hasNext();){
            String value=it.next();
            System.out.println(value);
        }
    }

 

4.3 Iterator Iteration Set Interface Type Container

package studyweek5 container;

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

public class IteratorSetTest {
    public static void main(String[] args) {
        Set<String> set=new HashSet<>();
        set.add("a");
        set.add("b");
        set.add("c");
        //Get Iterator Object
        //Through a while loop
        Iterator<String> iterator =set.iterator();
        while(iterator.hasNext()){
            String value=iterator.next();
            System.out.println(value);
        }
        //Through a for loop
        for(Iterator<String> it=set.iterator();it.hasNext();){
            String value=it.next();
            System.out.println(value);
        }
    }
}

4.3 Delete elements in iterators

package studyweek5 container;

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

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");
        //If you want to delete elements in the for loop, you must add judgment
        /*for(int i=0;i< list.size();i++){
            if("c".equals(list.get(i))){
                list.remove(i);
            }
            System.out.println(list.get(i));
        }*/
        int flag=-1;
        for (int i=0;i< list.size();i++){
            if("c".equals(list.get(i))){
                flag=i;
            }
            if(flag>-1){
                list.remove(flag);
            }
        }
        for(String str:list){
            System.out.println(str);
        }


        //Delete element in iterator
        Iterator<String> iterator=list.iterator();
        while(iterator.hasNext()){
            String value=iterator.next();
            if("c".equals(value)){
                iterator.remove();
            }
        }

        for(Iterator<String> it=list.iterator();it.hasNext();){
            System.out.println(it.next());

        }
    }
}

The final iteration method is determined by itself, iterators, enhanced for loops, for loops are chosen according to your preferences, which are essentially consistent

5. Collections Tool Class

 

 

5.1 Sort LIst containers

package studyweek5 container;

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

public class CollectionsSortTest {
    public static void main(String[] args) {
        List<String> list=new ArrayList<>();
        list.add("c");
        list.add("d");
        list.add("b");
        list.add("a");

        //Complete the sorting by the sort method in the Collection tool class
        Collections.sort(list);
        for(String str:list){
            System.out.println(str);
        }
    }
}

5.2 Random sorting of List-type containers

package studyweek5 container;

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

public class CollectionsSortTest {
    public static void main(String[] args) {
        List<String> list2=new ArrayList<>();
        list2.add("a");
        list2.add("b");
        list2.add("c");
        list2.add("d");
        //Complete the unordering through the shuffle method in the Collection tool class
        Collections.shuffle(list2);
        for(String str:list2){
            System.out.println(str);
        }
        System.out.println("---------------------");
    }
}

Topics: Java Back-end