HashMap and int as key

前端 未结 11 2063
说谎
说谎 2020-11-28 23:32

I am trying to build a HashMap which will have integer as keys and objects as values.

My syntax is:

HashMap myMap = new HashMap&         


        
11条回答
  •  天涯浪人
    2020-11-29 00:12

    HashMap does not allow primitive data types as arguments. It can only accept objects so

    HashMap myMap = new HashMap();
    

    will not work.

    You have to change the declaration to

    HashMap myMap = new HashMap();
    

    so even when you do the following

    myMap.put(2,myObject);
    

    The primitive data type is autoboxed to an Integer object.

    8 (int) === boxing ===> 8 (Integer)
    

    You can read more on autoboxing here http://docs.oracle.com/javase/tutorial/java/data/autoboxing.html

提交回复
热议问题