Home  >  Article  >  Java  >  The use of Map interface in Java and summary of interview knowledge points

The use of Map interface in Java and summary of interview knowledge points

WBOY
WBOYforward
2022-07-20 14:17:461552browse

This article brings you relevant knowledge about java, which mainly organizes the use of Map interface and related questions about interview knowledge points, including the storage characteristics of Map interface, commonly used implementation classes, Let’s take a look at the creation methods, common methods, etc., I hope it will be helpful to everyone.

The use of Map interface in Java and summary of interview knowledge points

Recommended study: "java video tutorial"

Map interface

Storage features

  • Stored in the form of key (key) value (value) pairs

  • The keys are unordered, have no subscripts, and the elements cannot be repeated

  • The values ​​are unordered, have no subscripts, and the elements can be repeated

Commonly used implementation classes

  1. HashMap
    • JDK1.2 underlying hash table implementation is thread-insecure and highly efficient
  2. LinkedHashMap
    • JDK1.2 is a subclass of HashMap. The underlying hash table implementation is thread-safe and highly efficient
  3. TreeMap
    • JDK1.2 is the implementation class of SortedMap. The underlying red-black tree implementation is thread-unsafe and highly efficient
  4. HashTable
    • JDK1.0 underlying hash table implementation is thread-safe and inefficient
  5. Properties
    • JDK1.0 is a subclass of HashTable. The underlying hash table is thread-safe and has low efficiency.

Creation method

  • Use polymorphism

Map<Generics of keys, generics of values> Collection name=new Implementation class name<Generics of keys, generics of values >();

tips: A key-value pair is an element

Common methods

  • Value put(key, value): Add a key-value pair to the end of the collection

    • If the key already exists, replace the value
  • void clear(): Clear the collection elements

  • boolean containsKey(key): Judge the collection Whether a certain key exists in the collection

  • boolean containsValue(value): Determine whether a certain value exists in the collection

  • Value get(key): Get the value corresponding to the key

  • ##boolean isEmpty(): Determine whether the collection content is empty, cannot be compared null value

  • void putAll(Map collection name): Add the contents of the specified Map collection to the end of the current collection

  • Value remove(key): Remove the key-value pair corresponding to the key

  • ##int size()

    : Get the collection key value Number of pairs

Code example:

public class Test {
    public static void main(String[] args) {
        //数字-String   1 - 一   1 - yi
        Map<Integer, String> map = new HashMap<Integer, String>();
        map.put(1, "一");
        map.put(111, "yiyiyi");
        map.put(666, "liuliuliu");
        map.put(111, "一一一");

        System.out.println(map.containsKey(678));//f
        System.out.println(map.containsValue("yiyiyi"));//t

        System.out.println(map.get(111));

        map.remove(666);
        System.out.println(map.get(666));

        System.out.println(map.size());//2
    }}
Traversal method

1,
    keySet( ) get()
  • Get all the keys first, then traverse the keys to get all the values
    • Set keySet(): Get all the keys stored in the Set collection and return
            //获取所有键
            Set<键的泛型> set=集合名.keySet();
            //遍历所有键
            set.forEach(
                o-> 
                //o就代表当前正在被遍历的键
                //通过集合名.get(o)可以得到对应的值
            );如:		Map<Integer, String> map = new HashMap<>();
            map.put(123, "yiersan");
            map.put(234, "ersansi");
            map.put(456, "siwuliu");
            map.put(999, "jiujiujiu");
            Set<Integer> set=map.keySet();
            set.forEach(o-> System.out.println("键:"+o+",值:"+map.get(o)));
2、
    values()
    • Get all the values ​​directly
    • Collection values(): Get all the values ​​stored in the Collection and return
    Collection<值的泛型> coll = 集合名.values();coll.forEach(v-> v就代表当前的值);如:		Collection<String> coll = map.values();
            coll.forEach(v-> System.out.println(v));
3、
    entrySet()
    • Get the key value and traverse the object
    • Set< Map.Entry > entrySet() : Get all the key-value pair objects stored in the Set collection and return
    • Set< Map.Entry< the generic type of the key, the generic type of the value> > is equivalent to the Set< key Value pair object>
    • getKey(): Get the key in the Entry object
    • getValue(): Get the value in the Entry object
            //获取键值对对象集合
            Set<Map.Entry<键的泛型,值的泛型>> set2=集合名.entrySet();
            for (Map.Entry entry : set2) {
                //通过entry.getKey()获取键
                //通过entry.getValue()获取值
            }如:        Set<Map.Entry<键的泛型,值的泛型>> set2=集合名.entrySet();
            for (Map.Entry entry : set2) {
                System.out.println("键:"+entry.getKey()+",值:"+entry.getValue())
            }
            System.out.println("lambda自遍历:");
            set2.forEach(entry-> System.out.println("键:"+entry.getKey()+",值:"+entry.getValue()));
4,
    Self-traversal forEach
  • JDK8.0
            集合名.forEach(new BiConsumer<键的泛型, 值的泛型>() {
                @Override
                public void accept(键的泛型 i, 值的泛型 s) {
                    //i代表键
                    //s代表值
                }
            });
            System.out.println("lambda简化自遍历:");
            map.forEach((k,v)-> k代表键,v代表值);如:
    		map.forEach(new BiConsumer<Integer, String>() {
                @Override
                public void accept(Integer i, String s) {
                    System.out.println("键:"+i+",值:"+s);
                }
            });
            System.out.println("lambda简化自遍历:");
            map.forEach((k,v)-> System.out.println("键:"+k+",值:"+v));
  • Use of different implementation classes

  • HashMap

    Yes Store null values. The key can store 0-1 nulls, and the value can store 0-n nulls

  • ##LinkedHashMap
  • can ensure that the order of storage and withdrawal is consistent

  • TreeMap
  • Can be sorted in ascending order by default according to the key

    Cannot sort null by default

      If the key is custom type, you must set the sorting rules in the same way as TreeSet
  • HashTable
  • Cannot store null values

  • Properties
  • Keys and values ​​must be of type String

    Polymorphism is not recommended for creation

      Generics cannot be declared
    Supplementary knowledge points for set interviews

    Set
  • is a set with only keys and no values

    Map

    The underlying array length is
  • 16
  • The array loading factor is
  • 75%
  • , when the array bit usage reaches 75% , the array will be expanded in a

    balanced binary tree way. The expansion length is the original length *2, and the length of each expanded array is 16

  • Why does Set or Map store values ​​from small to large?

    • When the stored value is too small, the integer value itself is its storage subscript, and the subscript is from small to large, so the value is also stored from small to large
  • The red-black tree uses the binary search method, which is characterized by fast query efficiency

  • Red-black tree: Use the hash code value as the criterion. If the hash code value is larger than the current element, store it to the right. If the hash code value is smaller than the current element, store it to the left.

  • Binary search method: Characterized by locking half of the data at a time

  • When the length of a linked list in the hash table array reaches 8 When, it will reorganize the linked list elements and open the red-black tree

Recommended learning: "java video tutorial"

The above is the detailed content of The use of Map interface in Java and summary of interview knowledge points. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete