2014-10-18 86 views
0

當我嘗試使用其中的「ObjectEpisodes」對我的數組列表進行排序時,我收到一個NullPointerException。NullPointer排序時ArrayList

當我嘗試對ArrayList進行排序但是其中一些對象沒有排序日期時,會出現空指針。我通過JSON和API調用獲取這些信息。

處理這些空指針的最佳方法是什麼?

我的目標實現可比:

 public Date getDateTime() { 
      return convertDate(getAirdate()); 
     } 

     public Date convertDate(String date) 
     { 
      SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); 
      Date inputDate = null; 
      try { 
       inputDate = dateFormat.parse(date); 
      } catch (ParseException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
      return inputDate; 
     } 

     @Override 
     public int compareTo(SickbeardEpisode another) { 
      return getDateTime().compareTo(another.getDateTime()); 
     } 

這裏是我的調用Collections.sort(集):

private static List<ObjectEpisodes> parseEpisodes(String url) { 
     List<ObjectEpisode> episodes = new ArrayList<ObjectEpisode>(); 

     String json = download(url); 

     try { 
      JSONObject result = new JSONObject(json); 
      JSONObject resultData = result.getJSONObject("data"); 
      Iterator<String> iter = resultData.keys(); 
      while (iter.hasNext()) { 
       String key = iter.next(); 
       JSONObject value = resultData.getJSONObject(key); 
       ObjectEpisode episode = new ObjectEpisode(value); 
       series.add(serie); 
      } 
     } 
     catch (JSONException e) 
     { 
      e.printStackTrace(); 
     } 

     Collections.sort(episodes); 

     return series; 
    } 

回答

1

如果您需要處理null我會改變這個

@Override 
public int compareTo(SickbeardEpisode another) { 
    return getDateTime().compareTo(another.getDateTime()); 
} 

類似於

@Override 
public int compareTo(SickbeardEpisode another) { 
    Date d = getDateTime(); 
    if (d == null) { 
    if (another == null || another.getDateTime() == null) return 0; 
    return -1; 
    } 
    return d.compareTo(another.getDateTime()); 
} 
0

我相信當你解析日期值的NPE生成:

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); 
dateFormat.parse(null) // java.lang.NullPointerException 

你可以檢測空,那麼在這種情況下返回null或defencive值,它取決於你的業務邏輯。在你正確處理NPE之後,你應該考慮的另一件事是在排序之後,在集合的前面或後面放置空值的位置。