Storing a new object as the value of a hashmap?

前端 未结 5 431
灰色年华
灰色年华 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:20

    Make use of the generics added to java. They help with both compile-time type-checking and they make the casts unnecessary.

      HashMap  mapper = new HashMap();
      //you will be able to retrieve an object and then cast it to your InfoStore
      InforStore isN01 = (InfoStore)mapper.get("N01");
    
      //this will unfortunately be accepted, even thought it's a bug
      mapper.put("N02", new Integer(0));
    
      ________________________
    
      HashMap  mapper = new HashMap();
      //you will be able to retrieve an object and then cast it to your InfoStore
      InforStore isN01 = mapper.get("N01"); //no cast
    

提交回复
热议问题