首先,我的代码(缩短):
import java.util.Vector;
public class GameField {
private Vector rooms = new Vector();
public void generateRooms() {
for (int i = 0; i < 10; i++) {
rooms.add(new Room(x, y, width, height));
}
}
}
我知道Vector类是通用的,但是我们还没有学过它们,我们应该像这样使用它。
当我调用方法generateRooms()
时,它不会按预期添加十个房间,但每个循环增加一个房间,如果它到达循环的开头则再次删除房间。
最后,我在Vector中只有一个房间,而不是十个房间。
为什么会这样?是因为我不使用泛型类型或者还有什么导致这种行为?
答案 0 :(得分:0)
我让generateRooms
函数返回room
向量,它运行正常:
public class Room {
int x;
int y;
int width;
int height;
public Room(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
}
class Main {
private Vector rooms = new Vector();
public Vector generateRooms() {
for (int i = 0; i < 10; i++) {
rooms.add(new Room(1 * i, 2, 3, 4));
}
return rooms;
}
public static void main(String[] args) {
Main m = new Main();
Vector r = m.generateRooms();
for (int i = 0; i < 10; i++) {
Room room = (Room) r.get(i);
System.out.println(room.x + " " + room.y + " " + room.width + " " + room.height);
}
}
}