2017-10-19 316 views
-2

我有這樣的功能:的Android - Collections.sort - 顯示java.lang.NullPointerException

final ArrayList<Addressable> tempStoreList = new ArrayList<>(); 
tempStoreList.addAll(addressables); 

    Collections.sort(tempStoreList, new Comparator<Addressable>() { 
     @Override 
     public int compare(Addressable o1, Addressable o2) { 

      double distanceToO1 = 0; 
      double distanceToO2 = 0; 

      if (o1.getAddress() == null) { 
       return (o2.getAddress() == null) ? 0 : -1; 
      } 
      if (o2.getAddress() == null) { 
       return 0; 
      } 

      if (userLocation != null && o1.getAddress() != null && o2.getAddress() != null) { 
       distanceToO1 = GlobalUtilities.distance(userLocation, o1.getAddress().getLocation(), "K"); 
       distanceToO2 = GlobalUtilities.distance(userLocation, o2.getAddress().getLocation(), "K"); 
      } 

      if (distanceToO1 < distanceToO2) { 
       return -1; 
      } else if (distanceToO1 > distanceToO2) { 
       return 1; 
      } else { 
       return 0; 
      } 

     } 
    }); 

出於某種原因,我不斷收到一個NPE:

if (o2.getAddress() == null) { 
    return 0; 
} 

這對我來說意味着空以某種方式放置在陣列中。任何人都曾遇到過這個?

+0

'addressables'已經包含了'null'。在那裏檢查。 – Henry

+0

Null是一個有效的列表值 – Mike

+1

找出爲什麼你的序列包含一個空元素並修復_that_問題。對於序列不包含空元素的情況,可以用Comparator.nullsFirst或Comparator.nullsLast(假設Java 8或更高版本)封裝「Comparator」。請注意,Comparator實現不需要支持空值,所以如果這是你想要處理的事情,你應該使用前面提到的包裝器之一。 –

回答

1

這意味着你需要檢查o2的參考。它可能爲空。在從o2.getAddress獲取地址之前,首先檢查o2 == null

1

是的,您可以在數組列表中包含空元素。

試試這個:

final ArrayList<Object> list = new ArrayList<Object>(); 
list.add(null); 

所以,如果你不能保證你將永遠有有效的對象,更改您的代碼

if (o2 == null || o2.getAddress() == null) { 
    return 0; 
} 
相關問題