Map collection, hashMap stored procedures, Set collection

1. Map interface

Features of the Map interface

  1. The map collection is structured as key-value pairs, KEY and VALUE, Map. Mapping relationship of Entry<K,V>

  2. The key value in map does not allow duplication, if duplicated, the corresponding value will be overwritten

  3. Mapping relationships in map s are out of order

  4. Maps do not have their own iterators, so iterations often require conversion to set sets to iterate

Summary of Map Collection Methods

Simple method:

void clear() empties the set boolean equals(Object o) to determine if the set object and parameter o are equal int hashCode() returns the hash code value boolean isEmpty() of this set to determine if the set is empty int size() returns the number of key-value pairs in this set

Operations between individual sets of map s

The boolean containsKey(Object key) determines whether the map contains the specified key boolean containsValue(Object value) determines whether the map contains the specified value V get(Object key) and returns the corresponding value based on the specified key, if it does not exist. Returns null V remove(Object key) Deletes the key-value pair V put(K key, V value) corresponding to the parameter key in this set Add mapping relationships (key-value pairs) void putAll (Map<> m) Add all mapping relationships (key-value pairs) of the M set to this set

Iteration of map

Collection values() takes the Value value from this map into a Collection and returns the Collection Set keySet() takes the Key value from this map into a Set set and returns the Set set <Map. Entry<K, V> entrySet () treats each pair of KV s in this map as an Entry, removes all Entries into a Set set, and returns the Set set

package cn.tedu.map;

import java.util.*;

/*This class is used to test map interfaces*/
public class MapDemo {
    public static void main(String[] args) {
        //1. Create map objects
        /*Map To conform to the mapping rules, you need to set both k and v data types
         * What types of k and v are specified depends on the specific requirements of the business*/
        Map<Integer, String> map = new HashMap();
        //2. Storing data in a Map collection depends on the specific requirements of the business
        map.put(9527, "Osteoprotein");
        map.put(9528, "Ursolin");
        map.put(9529, "Carp essence");
        map.put(9530, "Yellow-haired monster");
        map.put(9531, "Ursolin");
        map.put(9527, "Daughter King");
        System.out.println(map);//{9527=white bone essence, 9528=black bear essence, 9529=carp essence, 9530=yellow hair monster}
        /*1.map All that's in it is disordered data
         * 2.map Value in value in can be repeated
         * 3.map The key in does not allow duplication, if duplicated, the new value will overwrite the old value
         * For example, the key s of the King of the Daughter Kingdom and the white bone sperm are 9527, and the white bone sperm is covered up*/

        //3. Conduct method testing
//        map.clear(); // Empty Collection
//        System.out.println(map);//{}
        System.out.println(map.equals("Yellow-haired monster"));//false, to determine if the yellow hair monster is equal to the set object
        System.out.println(map.isEmpty());//Determine if it is empty false
        System.out.println(map.size());//5, get the number of key-value pairs in the map set
        System.out.println(map.containsKey(9527));//true, determines if the map collection contains the specified key-key
        System.out.println(map.containsValue("Osteoprotein"));//false, to determine if the map collection contains value-values

        //Remove all the value values from the map Collection and place them in the Collection.
        //The type of Type in Collection<Type>depends on the type of value in the map
        Collection<String> values = map.values();
        System.out.println(values);//[Daughter King, black bear essence, carp essence, yellow hair monster, black bear essence]

        //4. Iteration of map set 1
        /*We descend the demon spectrum to traverse the data in the map, but the map collection itself does not have its own iterator.
        * So you need to convert the map set to the Set set before iterating using the set iterator
        * Code: Set<Key>=Map. KeySet();
        * Role: Remove all key values from the map and store them in the set collection, where the generic of set is Integer
       */
        Set<Integer> set = map.keySet();//Converts a map collection to a set collection in which the key of the map is stored
        System.out.println(set);//[9527, 9528, 9529, 9530, 9531]
        Iterator<Integer> it = set.iterator();
        while(it.hasNext()){
//        System.out.print(it.next()+" ");//9527 9528 9529 9530 9531
            Integer key = it.next();
            String value = map.get(key);
            System.out.print("("+key+"="+value+")");//(9527 = King of the Daughter Kingdom) (9528 = black bear essence) (9529 = carp essence) (9530 = yellow hair monster) (9531 = black bear essence)
        }
        //5. Iteration of map 2
        /*To traverse a map collection, you need to first convert the map collection to a set collection
        * This scheme is a pair of key-value pairs treated as an Entry
        * Code: Map. Entry<key, value>=map. EntrySet();
        * Map.Entry<k,v>,Here is Map. Entry<Integer, String>*/
        System.out.println("entrySet(--------------------)");
        System.out.println();
        Set<Map.Entry<Integer, String>> set2 = map.entrySet();
        Iterator<Map.Entry<Integer, String>> iterator = set2.iterator();
        while (iterator.hasNext()){
            Map.Entry<Integer, String> entry = iterator.next();
            Integer key = entry.getKey();
            String value = entry.getValue();
            System.out.print("*"+key+"-"+value+"*");//*9527-Daughter King**9528-Black Bear Essence**9529-Carp Essence**9530-Yellow Hair Monster**9531-Black Bear Essence*
        }
    }
}

 

2. Storage procedures for HashMap:

  1. HashMap is structured as an array + a list of chains or an array + a red-black tree

  2. The Entry[] array at the bottom of HashMap, with an initial capacity of 16, a load factor of 0.75f, and an expansion of approximately twice

  3. When storing data, the location where the data is stored is calculated based on the hash(key)%n algorithm. n is the length of the array, which is actually the capacity of the collection.

  4. Data is stored directly when the calculated location has not previously been stored

  5. A hash conflict/hash collision occurs when there is data at the calculated location. The solution is to use a chain table structure and insert a new element after the specified location in the array, that is, the elements in the array are the first nodes to join.

  6. If the length of the chain table is > 8 and the array length is > 64, the chain table is converted to a red-black tree, and when the length of the chain table is < 6, it is restored to a chain table

 

 

 

package cn.tedu.map;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/*Practice*/
public class Demo {
    public static void main(String[] args) {
        //1. Create map objects
        /*Map To conform to the mapping rules, you need to set both k and v data types
         * What types of k and v are specified depends on the specific requirements of the business*/
        Map<Integer, String> map = new HashMap();
        //2. Storing data in a Map collection depends on the specific requirements of the business
        map.put(9527, "Osteoprotein");
        map.put(9528, "Ursolin");
        map.put(9529, "Carp essence");
        map.put(9530, "Yellow-haired monster");
        map.put(9531, "Ursolin");
        map.put(9527, "Daughter King");
        System.out.println(map);//{9527=white bone essence, 9528=black bear essence, 9529=carp essence, 9530=yellow hair monster}
        /*Iteration mode one*/
        Set<Integer> set = map.keySet();
        Iterator<Integer> it = set.iterator();
        while (it.hasNext()) {
            Integer key = it.next();
            String values = map.get(key);
            System.out.println("*" + key + "=" + values);
        }
        /*Iteration Mode Two*/
        Set<Map.Entry<Integer, String>> entries = map.entrySet();
        Iterator<Map.Entry<Integer, String>> entry = entries.iterator();
        while (entry.hasNext()) {
            Map.Entry<Integer, String> entrys = entry.next();
            System.out.println(entrys.getKey());
            System.out.println(entrys.getValue());
        }
    }
}

 

3. Set interface

Features of Set Interface

The set set collection has no duplicate elements The set collection has elements that are out of order The set collection can store null values, and null has at most one of our custom objects If you want to heavy, you need to add overridden equals() and hashCode() to the custom class

The Method of Collective Learning

Learn the common methods of the parent, the way subclasses are created, and the characteristics of collections

List s are mostly subscript related operations Set s are usually de-weighted operations Maps are usually map ping relationships, that is, key-value pairs of API s are often practiced, methods have no relationship with each other, which one to use, which one to find

package cn.tedu.collection;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;

/*This class is used to test Set s*/
public class TestSet {
    public static void main(String[] args) {
        //1. Create a collection object
        HashSet<String> set = new HashSet<>();
        set.add("Cabernet Fairy");
        set.add("Supreme Treasure");
        set.add("spider goblin");
        set.add("Cabernet Fairy");
        System.out.println(set);//[Spider essence, Supreme treasure, purple fairy]
        /*1.Set The elements in the collection are out of order
         * 2.Set Elements in a collection cannot be repeated and have no effect
         * Set Collection can hold null values, only one*/
        set.add(null);
        set.add(null);
        System.out.println(set);//[Spider essence, null, Supreme treasure, purple saffron]
        System.out.println(set.contains("Tang Monk"));//false, to determine if the collection contains Tang monks
        System.out.println(set.isEmpty());//false
        System.out.println(set.remove(null));//true
        System.out.println(set);//[Spider essence, Supreme treasure, purple fairy]
        System.out.println(set.size());//3
        System.out.println(Arrays.toString(set.toArray()));//[Spider essence, Supreme treasure, purple fairy]

        HashSet<String> set2 = new HashSet<>();
        set2.add("Cerebellar clothing");
        set2.add("Rabbit Paper");
        set2.add("Hippophae sinensis");
        set2.add("Favourite");
        System.out.println(set2);//[Rabbit paper, Favourite, Cerebellar clothing, Hippocampus hippocampus]

        set.addAll(set2);
        System.out.println(set);//[Spider essence, rabbit paper, fat butterflies, cerebellar clothing, Supreme treasure, hippocampus, purple fairy]
        System.out.println(set.containsAll(set2));//true
        System.out.println(set.removeAll(set2));//true
        System.out.println(set.contains(set2));//false
//        set.retainAll(set2);
//        System.out.println(set);// [], no public elements

        /*Set iteration*/
        Iterator<String> it = set2.iterator();
        while(it.hasNext()){
            System.out.print(it.next()+" ");//Haiteng Butterfly cerebellum
        }

    }
}

 

package cn.tedu.pojo;

import java.util.Objects;

public class Student {
    private  String name;
    private  Integer age;
    private  char sex;

    public Student(String name, Integer age, char sex) {
        this.name = name;
        this.age = age;
        this.sex = sex;
    }

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

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

    public char getSex() {
        return sex;
    }

    public void setSex(char sex) {
        this.sex = sex;
    }

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

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

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



package cn.tedu.collection;
import cn.tedu.pojo.Student;
import java.util.HashSet;
/*This class is used to test the weight removal of custom class objects*/
public class TestSet2 {
    public static void main(String[] args) {
        HashSet<Student> set = new HashSet<>();
        Student s1 = new Student("Qin Xiaoyan",18,'female');
        Student s2 = new Student("xxx", 30, 'male');
        Student s22 = new Student("xxx", 30, 'male');
        /*If set holds our custom type
         * You need to add overridden equals() and hashCode() to your custom class to remove the weight
         * Otherwise, you would think that the address values of s2 and s22 are different, they are two different objects and will not be duplicated*/
        set.add(s1);
        set.add(s2);
        set.add(s22);
        System.out.println(set);
    }
}

 

Keywords: data structure

Added by jwalsh on Sun, 23 Jan 2022 02:08:17 +0200