HashMaps and Null values?

前端 未结 2 996
余生分开走
余生分开走 2021-02-11 12:07

How do you pass in null values into a HashMap?
The following code snippet works with options filled in:

HashMap options = new HashMap         


        
2条回答
  •  抹茶落季
    2021-02-11 12:20

    You can keep note of below possibilities:

    1. Values entered in a map can be null.

    However with multiple null keys and values it will only take a null key value pair once.

    Map codes = new HashMap();
    
    codes.put(null, null);
    codes.put(null,null);
    codes.put("C1", "Acathan");
    
    for(String key:codes.keySet()){
        System.out.println(key);
        System.out.println(codes.get(key));
    }
    

    output will be :

    null //key  of the 1st entry
    null //value of 1st entry
    C1
    Acathan
    

    2. your code will execute null only once

    options.put(null, null);  
    Person person = sample.searchPerson(null);   
    

    It depends on the implementation of your searchPerson method if you want multiple values to be null, you can implement accordingly

    Map codes = new HashMap();
    
        codes.put(null, null);
        codes.put("X1",null);
        codes.put("C1", "Acathan");
        codes.put("S1",null);
    
    
        for(String key:codes.keySet()){
            System.out.println(key);
            System.out.println(codes.get(key));
        }
    

    output:

    null
    null
    
    X1
    null
    S1
    null
    C1
    Acathan
    

提交回复
热议问题