views:

140

answers:

2

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;

 }
+10  A: 
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.

Michael Borgwardt
I can not do something that you have written above because this error will be shown"can not create a generic array of V
Johanna
Use a collection like an ArrayList<V> instead then.
banjollity
How can I use ArrayList<V> here???
Johanna
Alternatively, if you must use an array, use Object[] a = new Object[100];
extraneon
And have the program crash on larger inputs? Bad idea.
Michael Borgwardt
As for how to use an ArrayList: simply replace all instances of array index access with calls to get() and set().
Michael Borgwardt
+4  A: 

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.

Herms