Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 排序ArrayList时使用空指针_Java_Json_Sorting_Arraylist_Collections - Fatal编程技术网

Java 排序ArrayList时使用空指针

Java 排序ArrayList时使用空指针,java,json,sorting,arraylist,collections,Java,Json,Sorting,Arraylist,Collections,当我试图用“ObjectScents”对arraylist进行排序时,我得到了一个NullPointerException 当我尝试对ArrayList进行排序时,会出现空指针,但有些对象没有排序日期。我通过JSON和API调用获取这些信息 处理这些空指针的最佳方法是什么 我的对象实现了: public Date getDateTime() { return convertDate(getAirdate()); } p

当我试图用“ObjectScents”对arraylist进行排序时,我得到了一个NullPointerException

当我尝试对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());
        }
以下是我的电话收集。分类(剧集):

私有静态列表(字符串url){
列表集=新建ArrayList();
字符串json=下载(url);
试一试{
JSONObject结果=新的JSONObject(json);
JSONObject resultData=result.getJSONObject(“数据”);
迭代器iter=resultData.keys();
while(iter.hasNext()){
String key=iter.next();
JSONObject值=resultData.getJSONObject(键);
ObjectSpidence=新的ObjectSpidence(值);
系列。添加(系列);
}
}
捕获(JSONException e)
{
e、 printStackTrace();
}
收藏。分类(剧集);
返回序列;
}

如果您需要处理
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());
}

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

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.parse(null) // java.lang.NullPointerException
您可以检测null,然后返回null或防御值。在这种情况下,这取决于您的业务逻辑。在正确处理NPE之后,您应该考虑的是在被排序后,在集合的前面或后面放置空值。
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.parse(null) // java.lang.NullPointerException