1

我正在尝试运行一个模拟,其中在 for 循环中生成了一系列人,然后我在不同的类中使用它们来执行某些任务。

我不太确定如何生成 n 个人员对象,同时让程序都可以访问它们(即具有变量名,以便我可以使用他们的方法)

4

3 回答 3

2

-使用Collection框架

- Map将适合此实施。

Map<String,Person> personMap = HashMap<String,Person>();

personMap.put("person1",new Person("Vivek"));
personMap.put("person2",new Person("Vicky"));
于 2012-10-06T13:21:29.043 回答
1

您通常无法从正在运行的程序中创建新的源代码(除非您使用字节码生成和类加载器,我认为您在这里不需要)。

代替

Person a = new Person("A");
Person b = new Person("B");
a.doStuff();
b.doStuff();

考虑有一张地图(未经测试):

Map<String, Person> map = new HashMap();
map.put("a", new Person("A"));
map.put("b", new Person("B"));

map.get("a").doStuff(); // on A
map.get("b").doStuff(); // on B
于 2012-10-06T13:13:49.250 回答
1

您可以使用数组。

// create people
int n = 30;
Human[] human = new Human[n];    
for (int i=0; i<n; i++) {
  human[i] = new Human();
}

// access specific person
human[3].doSomething();
// access all people
for (Human h:human) {
  h.doSomething();
}

替代方案:使用人员列表/集合/地图。

于 2012-10-06T13:14:05.890 回答