简体   繁体   中英

“Exception in thread ”main" java.lang.NullPointerException when adding to a HashMapList

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]

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 = ...".

look at your constructor.

new HashMap<Integer, V>();

should be

map = new HashMap<Integer, V>();

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM