Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Naming a new object after a string?

Tags:

java

I want to have a method that will create an object of the class being and automatically name it "b1" for the first object, "b2" for the second, and so on. Can I use a String as the name of a new object? If it's possible, how do I do it?

class being {
    static int count = 0;
    String name;

    void createbeing(){
        name = "b" + Integer.toString(count);
        being name = new being(); //Here I want to insert the String name as the name of the object
        count++;
    }

}
like image 791
Syntic Avatar asked Mar 16 '13 13:03

Syntic


People also ask

How do you use string names for objects?

string objectName = "myName"; Object [objectName] = new Object(); And then refer to it like: myName. method(parameter);

Can an object name be a string?

Unassigned properties of an object are undefined (and not null ). JavaScript object property names (keys) can only be strings or Symbols — all keys in the square bracket notation are converted to strings unless they are Symbols.


2 Answers

No, this is not possible in Java; you cannot create variables at runtime. You could, however, maintain a Map that maps String identifiers to their corresponding Beings. i.e.

Map<String, Being> map = new HashMap<String, Being>();
...
name = "b" + Integer.toString(count);
map.put(name, new Being());
count++;

Note that I have assumed a more conventional name: Being as opposed to being.

like image 178
arshajii Avatar answered Oct 07 '22 12:10

arshajii


In your code you are just creating a local reference of the class object in the function "createbeing()",and the above declared String "name" is hidden in the "createbeing()" function scope by the reference "name" that you are declaring as a reference of the object of class being.

like image 28
Shivam Dhabhai Avatar answered Oct 07 '22 12:10

Shivam Dhabhai