Storing a new object as the value of a hashmap?

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

    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());
    
    
    
    }
    

    }

提交回复
热议问题