排序ArrayList时的NullPointer

时间:2014-10-18 22:18:46

标签: java json sorting arraylist collections

当我尝试用“ObjectEpisodes”对我的arraylist进行排序时,我得到一个NullPointerException。

当我试图对ArrayList进行排序但是某些对象没有要排序的日期时,会出现空指针。我通过JSON和API调用获取这些信息。

处理这些空指针的最佳方法是什么?

My Object实现Comparable:

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

2 个答案:

答案 0 :(得分: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());
}

答案 1 :(得分:0)

我相信在解析日期值时会生成NPE:

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

您可以检测到null,然后在这种情况下返回null或defencive值,这取决于您的业务逻辑。在正确处理NPE之后,您应该考虑的另一件事是在排序后,在集合的前面或后面放置空值。