views:

450

answers:

3

HashMapList keeps its elements inside a HashMap) and when I call add method this error message will be shown in the concole "Exception in thread "main" java.lang.NullPointerException

public class HashMapList<K, V extends Product> extends AbstractList<Product> {
public V element;

public int index;

Map<Integer, V> map;

public HashMapList() {
 super();
 new HashMap<Integer, V>();
 }

// Override
public void add(int index, V element) {
 map.put(new Integer(index), element);

 }
}

thanks,I have solved the first problem but when I call add method like==>

HashMapList<Integer, Book> list = new HashMapList<Integer, Book>();
list.add(0, new Book("physics"));

and Book class is==>

public class Book extends Product {
public String name = null;
public Book(String name) {
 super(name);

   }
 }

and Product class is==>

public class Product implements Comparable {

/**
 * 
 */
private static final long serialVersionUID = 1L;

private String name = null;

public Product(String name) {
 if (name == null)
  throw new NullPointerException();
 this.name = name;
  }

public String getName() {
 return name;
  }

// Override

public int compareTo(Object o) {
 Product product = (Product) o;
 int compare = getName().compareTo(product.name);
 return compare;
  }
 }

And when I want to print this list basically with System.out.println(list); this sentence will be shown in the concole:[org.bihe.com1112.Book@1fb8ee3, org.bihe.com1112.Book@61de33, org.bihe.com1112.Book@14318bb]

+3  A: 

You are not assigning anything to map

public HashMapList() {
    super();
    map = new HashMap<Integer, V>();
}

whenever you get a null pointer exception look for where you assign a value to the variable to you are using. Here look for anywhere in your code where you say "map = ...".

djna
+2  A: 

look at your constructor.

new HashMap<Integer, V>();

should be

map = new HashMap<Integer, V>();
Ruggs
+2  A: 

For your second question, you should really start another thread. It is correctly printing the string representation of your object. Your Book class does not provide a custom overridden toString() method. So it uses the one inherited from Object, which just returns a string made of the full name of the class and the hashCode of the object, which is what you are seeing. You should override the toString() method if you want to see something different.

newacct
You mean toString() method and not .toString(), as methods can't start with a period.
Steve Kuo