I want to write a function in Java that takes a String as argument and creates an object with the same name

128 views Asked by At

Say I am getting names of people and want to create person objects of the same name, something like this :

void foo(String str){
       Person str = new Person();
}

So that later I can refer to the person by name, something like :

int getAcoountNumber(String str){
      return str.acNumber;
}
1

There are 1 answers

1
vmcloud On

I think you need a map for String str to Person str.

say the map is HashMap nameMap, and change the code like this:

void foo(String str){
    Person p = new Person(str);
    nameMap.put(str, p);
}

int getAcoountNumber(String str){
      return nameMap.get(str).acNumber;
}