Naming a new object after a string?

I want to have a method that will create an object of the class and automatically call it "b1" for the first object, "b2" for the second, etc. Is it possible to use String as the name of a new object? If possible, how can I do this?

 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++; } } 
+6
source share
5 answers

No, this is not possible in Java; you cannot create variables at runtime. However, you can save a Map that maps String identifiers to the corresponding Being s. i.e.

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

Please note that I have adopted a more conventional name: Being as opposed to Being .

+9
source

In your code, you simply create a local link to the class object in the "createbeing ()" function, and the above declared name "String" is hidden in the "createbeing ()" area via the "name" link that you declare a link to the class object.

+3
source

Can a string be used as the name of an object?

No. The usual way to do this is to use one of the List implementations and add objects to it, for example:

 class being{ static List<being> beings = new LinkedList<being>(); void createbeing(){ beings.add(new being()); } } 

(I am not advocating using a static list of creatures. There is almost certainly a better approach to the bigger problem you are trying to solve. But that was the minimal code for the code you presented.)

Alternatively, you can use Map and actually get the names you need ( "b1" , etc.):

 class being{ static int count = 0; static Map<String,being> beings = new HashMap<String,being>(); void createbeing(){ count++; beings.add("b" + count, new being()); } } 

(The same caution as above)

+2
source

Add the name attribute to your class (which should be named Being , BTW, not Being ) and its constructor:

 public class Being private String name; public Being(String name) { this.name = name; } } 

Then create your objects:

 void createBeing(){ name = "b" + Integer.toString(count); Being being = new Being(name); // TODO: do something with the Being object count++; } 

How an object can have a name. Do not confuse objects and variables.

+2
source

It's impossible. If the variable name is important to you, save it as the keys Map<String,being>

 Map<String,being> map = new HashMap<String,being>(); map.put("b1", new being()); 
+1
source

All Articles