Storing a new object as the value of a hashmap?

前端 未结 5 394
灰色年华
灰色年华 2020-12-15 23:33

I am trying to find a way to store a new instance of a class as the value in a Java hashmap. The idea was given to me by a Java instructor in order to create a data storage

5条回答
  •  有刺的猬
    2020-12-16 00:08

    The problem is that your code only specifies that the values in the map are Object. You know more than that, so tell the compiler that information:

    HashMap mapper = new HashMap();
    mapper.put("NS01", new InfoStor("NS01"));
    ...
    
    InfoStor value = mapper.get("NS01");
    Integer memory = value.getMemory();
    

    Note that it's generally though not always better to use interfaces for the variable types - and you can use the diamond operator for the constructor call, letting the compiler use type inference to fill in the type arguments:

    Map mapper = new HashMap<>();
    mapper.put("NS01", new InfoStor("NS01"));
    ...
    
    InfoStor value = mapper.get("NS01");
    Integer memory = value.getMemory();
    

提交回复
热议问题