-1

首先,我的代码(缩短):

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 中只有一个房间,而不是十个。

为什么会这样?是因为我不使用泛型类型还是导致这种行为的其他原因?

4

1 回答 1

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);
        }
    }
}
于 2013-04-14T19:33:54.040 回答