我想基于Position枚举类型创建100个新实例.在switch case语句中我有5个案例,并且基于enum类型我想创建相应的Employee实例.我的问题是,我不知道如何在每次创建新实例时创建和分配新的变量名,例如:worker1,worker2,worker3.这是我到目前为止所得到的:
final String randomVariableName() {
int count = 1;
String s = "worker" + count;
count++;
return s;
}
final Position randomPosition(){
return positions[random.nextInt(positions.length)];
}
public void run() {
for (int i = 1; i <= 100; i++) {
String randomName = "worker" + i;
Position p = randomPosition();
switch (p) {
case PROJECT_LEADER:
ProjectLeader randomVariableName() = new ProjectLeader(p, randomName, 5000);
case DEVELOPER_LEADER:
DeveloperLeader randomVariableName() = new DeveloperLeader(p, randomName, 1000);
}
}
Run Code Online (Sandbox Code Playgroud)
但是这样,我无法调用该randomVariableName()方法,因为:Variable 'randomVariableName' is already defined in the scope
我甚至不确定,这将是一个很好的解决方案.我只需要一种方法,在switch-case中创建100个唯一的引用变量名.
您无法在Java中在运行时创建新的变量名称.您可以做的是使用数组或集合来存储实例.
Employee employees[] = new Employee employees[100];
for (int i = 0; i < 100; i++) {
String randomName = "worker" + i;
Position p = randomPosition();
switch (p) {
case PROJECT_LEADER:
employees[i] = new ProjectLeader(p, randomName, 5000);
break;
case DEVELOPER_LEADER:
employees[i] = new DeveloperLeader(p, randomName, 1000);
break;
}
}
Run Code Online (Sandbox Code Playgroud)
在循环后,您可以访问employees[0]通过employees[99]让你的100个实例.
甚至比使用原始数组更合适的是集合,例如ArrayList<Employee>您添加实例的集合.
另外 - 记得在switch()内部中断你的case语句