簡體   English   中英

添加到HashMapList時,“主線程中的異常” java.lang.NullPointerException

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

HashMapList將其元素保留在HashMap中),當我調用add方法時,此錯誤消息將顯示在conole“線程“主”中的異常” 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);

 }
}  

謝謝,我已經解決了第一個問題,但是當我調用add方法時,例如==>

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

和Book類是==>

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

   }
 }

並且產品類別為==>

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;
  }
 }

當我想使用System.out.println(list)基本上打印此列表時; 此句子將顯示在concol中: [org.bihe.com1112.Book @ 1fb8ee3,org.bihe.com1112.Book @ 61de33,org.bihe.com1112.Book @ 14318bb]

您沒有為地圖分配任何內容

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

每當您得到空指針異常時,請尋找要在何處為使用的變量分配值。 在代碼中尋找“ map = ...”的任何地方。

看你的構造函數。

new HashMap<Integer, V>();

應該

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

對於第二個問題,您應該真正啟動另一個線程。 它正確打印了對象的字符串表示形式。 您的Book類沒有提供自定義的重寫toString()方法。 因此,它使用從Object繼承的Object ,該Object僅返回由類的全名和對象的hashCode組成的字符串,這就是您所看到的。 如果要查看其他內容,則應重寫toString()方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM