在字符串后命名一个新对象?

Syn*_*tic 6 java

我希望有一个方法可以创建类的对象,并"b1"为第一个对象自动命名,"b2"第二个,依此类推.我可以使用a String作为新对象的名称吗?如果有可能,我该怎么办?

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

}
Run Code Online (Sandbox Code Playgroud)

ars*_*jii 9

不,这在Java中是不可能的; 你不能在运行时创建变量.但是,您可以MapString标识符映射到相应的Beingsie

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

请注意,我假设一个更传统的名称:Being而不是being.