0

所以我正在使用集合设计模式并且正在使用数组列表。每当我尝试向数组列表中添加一些东西时,我都会得到一个 NPE。我可能错误地实现了集合,因此是 NPE。

我不想复制我的整个代码,因为它太长了,所以我想给大家一个 SSCCE。我不认为 ObjectA.java 和 Objects.java 的内容是必要的,因为在实现集合模式之前我没有得到任何 NPE。特别说明:我无法导入 Java 的迭代器。

//Game.java
public class Game {
    private World w;

    public Game() {
        w = new World();
        w.getList().add(new ObjectA()); //NPE here
    }
}

//World.java
public class World {
    private Collection list;

    public Collection getList() {
         return list;
    }
}

//Collection.java //I don't know what could cause the NPE so I show everything
public class Collection{
    private ArrayList<Objects> collection = new ArrayList<>(0);

    public Objects get(int i) {
        return collection.get(i);
    }
    public Objects remove(int i){
        return collection.get(i);
    }
    public int size() {
        return collection.size();
    }
    public void add(Objects o) {
        collection.add(o);
    }
    public Iterator getIterator() {
        return new CollectionIterator();
    }

    public class CollectionIterator {
       private int index;

       public CollectionIterator() {
           index--;
       }
       public boolean hasNext() {
           if (collection.size() <= 0 || currElementIndex == collection.size() - 1) return false;
           return true;
       }
       public Object getNext() {
           index++;
           return collection.get(index);
       }
       public void remove() {
           collection.remove(index);
           index--;
       }
   }
}
4

3 回答 3

1

Because the list in World class has not been initialized.

private Collection list; // Not yet initialized

and thus, the w.getList() returns an uninitialized list which throws a NPE when you call add() on it.

You need to initialize your list before using it.

private Collection list =  new ArrayList();
于 2013-11-05T05:23:48.307 回答
1

Problem is World.list is not initialized. Change the world class as given below:

public class World {
    private final Collection list = new ArrayList();

    public Collection getList() {
         return list;
    }
}
于 2013-11-05T05:24:59.130 回答
0

You have only declared but never initialized your list in World class:

private Collection list;

Try replacing this with:

private Collection list = new Collection();
于 2013-11-05T05:24:37.183 回答