Johanna
Johanna

Reputation: 27628

Why the NullPointerException will be thrown here?

this is my collection which I make:

Test<v> map = new Test<V>();

but when I call sort method which I override it in Test class and also map1 is one collection that I make it in the Test class which will keeps the elements that I add to the map collection,this exception will be thrown that it is for line 5:a[i] = map.get(new Integer(i));

    V[] a = null;
    public void sort() {
    V temp = null;

    for (int i = 0; i < map1.size(); i++) {

        a[i] = map1.get(new Integer(i));

        if (a[i].getName().hashCode() > a[i + 1].getName().hashCode())
            temp = a[i];
        a[i] = a[i + 1];
        a[i + 1] = temp;

    }

Upvotes: 0

Views: 282

Answers (2)

Michael Borgwardt
Michael Borgwardt

Reputation: 346270

V[] a = null;
...
a[i] = ...

There's your problem. A NullPointerException is not only thrown when trying to call a method on a null; trying to access an index in an array through a null will have the same effect. You have to instantiate the array, though in your case this is problematic since you're using a generic type. Use an ArrayList instead of an array.

Upvotes: 10

Herms
Herms

Reputation: 38798

You never assigned a value to a. At the very top you do:

V[] a = null;

but never assign anything to it after that. So, when you do:

a[i] = ...

a is null, so you get a null pointer exception.

Upvotes: 4

Related Questions