[英]Why the NullPointerException will be thrown here?
這是我的收藏:
Test<v> map = new Test<V>();
但是,當我調用在Test類中重寫它的sort方法,並且map1是我在Test類中創建的一個集合時,該集合將保留我添加到map集合中的元素,就會拋出該異常,因為它是針對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;
}
V[] a = null;
...
a[i] = ...
有你的問題。 NullPointerException
不僅在嘗試對null
調用方法時null
; 嘗試通過null
訪問數組中的索引將具有相同的效果。 您必須實例化數組,但是由於您使用的是泛型類型,因此在您的情況下這是有問題的。 使用ArrayList
而不是數組。
你永遠不賦值給a
。 在最頂層,您可以執行以下操作:
V[] a = null;
但此后再也不給它分配任何東西。 因此,當您這樣做時:
a[i] = ...
a為null,因此您將獲得null指針異常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.