【问题标题】:NullPointer while sorting ArrayList [duplicate]排序ArrayList时的NullPointer [重复]
【发布时间】:2014-10-18 22:18:46
【问题描述】:

当我尝试使用“ObjectEpisodes”对我的数组列表进行排序时,我收到了 NullPointerException。

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

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

我的对象实现了 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(episodes):

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

【问题讨论】:

    标签: java json sorting arraylist collections


    【解决方案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());
    }
    

    【讨论】:

      【解决方案2】:

      我相信 NPE 是在您解析日期值时生成的:

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

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

      【讨论】:

        猜你喜欢
        • 2017-10-06
        • 2021-11-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-29
        • 1970-01-01
        • 2020-01-20
        • 1970-01-01
        相关资源
        最近更新 更多