【发布时间】:2020-07-02 19:32:37
【问题描述】:
我目前的目标是将对象添加到向量中,以便由我创建的另一个类中的迭代器访问(对于这个项目,我不允许使用 Java 的迭代器)。我的迭代器函数应该返回向量内的特定对象。相反,迭代器在向量中报告空值。经过调试,问题是在启动时添加对象后,对象消失了。将向量传递给迭代器类并不能解决问题。我试过使用数组列表而不是向量,但没有成功。
public void init() { //where im doing the adding
for (int i = 0; i < 1; i++) {
cyborg = new Player(ColorUtil.rgb(42, 194, 225), 50, 46.0, baseLocations[0], 40, 100, 100, 0, 50, true);
go.add((Player) cyborg);
}
for (int i = 0; i < 3; i++) {
NPC = new NPC(ColorUtil.rgb(42, 194, 225), 50, 46.0, baseLocations[0], 40, 100, 100, 0, 50, currStrat);
go.add((NPC) NPC);
}
for (int i = 0; i < 2; i++) {
drone = new Drone(ColorUtil.rgb(82, 95, 81), r.nextInt(50), 10.0,
new Point(r.nextFloat() * 1000, r.nextFloat() * 1000), r.nextInt(50));
go.add(drone);
}
for (int i = 0; i < 4; i++) {
base = new Base(ColorUtil.rgb(169, 235, 0), baseSequence++, baseLocations[i], 10);
go.add((Fixed) base);
}
for (int i = 0; i < 2; i++) {
eStation = new eStation(ColorUtil.rgb(100, 85, 85), new Point(r.nextFloat() * 1000, r.nextFloat() * 1000),
r.nextInt(50), 100);
go.add((Fixed) eStation);
}
public class GameCollection implements ICollection {
private Vector<GameObject> gameCollection;
public GameCollection() {
gameCollection = new Vector<GameObject>(); //the vector im having problems with
System.out.println(gameCollection.toString()); //Test to check if objects in game collection array. Prints null values after startup
}
public IIterator getIterator() {
GameCollectionIterator gameItr = new GameCollectionIterator(gameCollection);
return gameItr;
}
public void add(GameObject o) {
gameCollection.addElement(o);
//System.out.println(super.toString());
}
public Object elementAt(int location) {
if(location < gameCollection.size()) {
return (Object) gameCollection.indexOf(location);
}
throw new ArrayIndexOutOfBoundsException(location);
}
public void remove(GameObject o) {
// TODO Auto-generated method stub
gameCollection.remove(gameCollection.indexOf(o));
}
private class GameCollectionIterator implements IIterator{
private int currIndex = 0;
private Vector <GameObject> game = new Vector <GameObject>();
public GameCollectionIterator(Vector<GameObject> g) {
game = g;
}
@Override
public boolean hasNext() {
if(game.size() <= 0){
System.out.println("First case");
return false;
}
if(currIndex == game.size() -1){
System.out.println("Second case");
return false;
}
return true;
}
@Override
public Object getNext() {
currIndex++;
return(game.indexOf(currIndex));
}
@Override
public void remove() {
game.remove(currIndex);
}
}
【问题讨论】:
-
阅读this article 了解调试代码的技巧。如果您仍需要帮助,请创建一个 minimal reproducible example,我们可以复制/粘贴并自行运行,并查看您所询问的相同行为。