adding a key to HashMap without the value?

前端 未结 5 2175
孤城傲影
孤城傲影 2021-02-19 14:37

Is there a way to add a key to a HashMap without also adding a value? I know it seems strange, but I have a HashMap> amd I wan

5条回答
  •  你的背包
    2021-02-19 14:52

    //This program should answer your questions
    import java.util.*;
    public class attemptAddingtoHashMap { //Start of program
    
    //MAIN METHOD #################################################
    
    public static void main(String args[]) {  //main begins
    
    Map> hmTrial = new HashMap>(); 
    
    ArrayList alTrial = new ArrayList();//No values now
    
    if (hmTrial.containsKey("first")) {
    hmTrial.put("first", alTrial); }
    
    else {hmTrial.put("first",alTrial);}
    //in either case, alTrial, an ArrayList was mapped to the string "first"
    //if you choose to, you can also add objects to alTrial later
    System.out.println("hmTrial is " + hmTrial); //empty now
    alTrial.add("h");
    alTrial.add("e");
    alTrial.add("l");
    alTrial.add("l");
    alTrial.add("o");
    System.out.println("hmTrial is " + hmTrial);//populated now
    
       } //end of main
    //#############################################################################################################
    
    } //end of class
    
    //Note - removing objects from alTrial will remove the from the hashmap
    //You can copy, paste and run this code on https://ide.geeksforgeeks.org/
    

提交回复
热议问题