Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

java - Naming a new object after a string?

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++;
    }

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...