Storing a new object as the value of a hashmap?

2020-02-10 03:58发布

问题:

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 structure that could be used to for a program I am working on.

The idea he recommended to me was to use a hashmap that stored the name of a computer as the key and the value would be a new instance of the class InfoStor.class. InfoStor contains methods such as getName(), setName(), getMemory()...

I have the class and the method pretty much setup for a basic test to see if it would work or not. The problem I am running into is I cannot figure out how to use the methods inside of InfoStor once I have created a new entry in the hashmap.

This is the code I have so far;

VMware.class

import java.util.HashMap;

public class VMware {

    public static void main(String[] args) {                       
        HashMap <String, Object> mapper = new HashMap();            
        mapper.put("NS01", new InfoStor("NS01"));            
        //mapper.get("NS01").            
    }            
}

InfoStor.class

public class InfoStor {

    private String vmName;
    private String platform;
    private Integer memory;

    public InfoStor (String name) {
        vmName = name;
    }

    String getName(){
        return vmName;
    }

    void setPlatform(String p){
        platform = p;
    }

    String getPlatform(){
        return platform;
    }

    void setMemory(Integer m){
        memory = m;
    }

    Integer getMemory(){
        return memory;
    }
}

What I am trying to accomplish is something like this (basic idea).

Object var = mapper.get("NS01");    
System.out.println(var.getMemory());

Am I going about this the wrong way? Any help is appreciated thanks.

回答1:

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<String, InfoStor> mapper = new HashMap<String, InfoStor>();
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<String, InfoStor> mapper = new HashMap<>();
mapper.put("NS01", new InfoStor("NS01"));
...

InfoStor value = mapper.get("NS01");
Integer memory = value.getMemory();


回答2:

If you declare your hashmap like so:

HashMap<String, InfoStor> mapper = new HashMap<String, InfoStor>();

Then when you get an object out of the mapper, it will be an instance of InfoStor (you won't need to cast it or worry about a class cast exception because it's not the rist class.)

So:

InfoStor myStor = mapper.get("somekey");
myStor.getMemory(); // this will work

Otherwise, if you stick with the HashMap<String, Object> you used in your original code, you'll need to cast it before you call the method:

Object obj = mapper.get("somekey");
((InfoStor)obj).getMemory(); // cast is required
obj.getMemory(); // this will not compile

You should read up on Java generics.



回答3:

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

  HashMap <String, Object> 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 <String, InfoStore> 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


回答4:

Youre on the right track...

Initialise the map as:

HashMap <String, InfoStor> mapper = new HashMap<String, InfoStor>();

Then after adding objects to the map retrieve them with:

InfoStor var = mapper.get("NS01");
System.out.println(var.getMemory());


回答5:

you can cook something by using array...for example if you can store objects in arrays then use that idea to achieve it in hash map...i dont knw how you design but i once got stuck in that and made through like this

example...

class princess{

int age;

public princess(int age){
    this.age=age;
}
public int getAge(){
    return this.age;
}

}

public class hashmaptest {

public static void main(String[] args) {
  princess[] p=new princess[10];
  HashMap scores = new HashMap();
  scores.put("a",new princess(6));
  scores.put("b",new princess(7));

  p[0]=(princess)scores.get("a");
   System.out.println(p[0].getAge());
  p[0]=null;
   p[0]=(princess)scores.get("b");

  System.out.println(p[0].getAge());



}

}



标签: java hashmap