开发者

Java Null Pointer Exception

I attempted to adapt a class I had found on the web for a dynamic array of ints for a dynamic array of "Entities," but now I am getting a "NullPointerException."

The code raising the exception is:

public void initialize()
{
    buffer = new BufferedImage(800,600,BufferedImage.TYPE_INT_RGB);
    Entities.put(Entities.getCurrentPos()+1, new Entity(100, 100, Color.green));
    Entities.put(Entities.getCurrentPos()+1, new Entity(400, 400, Color.blue));
}

The relevant parts of DynArrayEntities class:

...

private Entity[] data;  // An array to hold the data.
private int currentpos = 0;

...

public void put(int position, Entity value) {

    if (position >= data.length) {

        int newSize = 2 * data.length;
            if (position >= newSize)
                newSize = 2 * position;
        Entity[] newData = new Entity[newSize];开发者_运维技巧
        System.arraycopy(data, 0, newData, 0, data.length);
        data = newData;
    }

    data[position] = value;
    currentpos++;

}

....

public int getCurrentPos() {
    return currentpos;
}

Thanks in advance for your help!


...

private Entity[] data= new Entity[0];  // Or some value > 0
...

otherwise data is null the first time you access it in the method.


you're doing

position >= data.length

before initializing data


(Is Entities a field? In that case you should call it entities. See http://java.sun.com/docs/codeconv/)

You should tell exactly that on which line the NPE is thrown. If it's in the initialize() method's second line, then probably the Entities field is null. If it's in the put() method, then probably it's because the data field is null.


Are you doing this just as a learning exercise? If not, why not use java.util.Vector, which provides a dynamic array for any Object?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜