我有一个 List<object>
我在哪里有属性(property) manufacturedDate
我必须在哪里做sorting
.在List<Object>
有一些值为 null
对于 manufacturedDate
.排序不正确。我不确定是不是因为 null
值。 list
不按 manufacturedDate
的升序或降序返回值.
下面是我的代码:
if(sortType.equalsIgnoreCase("manufacturedDate"))
{
DateFormat sdf1 = new SimpleDateFormat("dd-MMM-yyyy", Locale.ENGLISH);
if(manufacturedDateSortAsc.equalsIgnoreCase("Desc"))
{
manufacturedDateSortAsc = "Asc";
Collections.sort(carList, new Comparator<CarDataTransferObject>()
{
public int compare(CarDataTransferObject object1, CarDataTransferObject object2)
{
int returnVal = 0;
try
{
returnVal = sdf1.parse(object1.getManufacturedDate()).compareTo(sdf1.parse(object2.getManufacturedDate()));
}
catch (Exception e)
{
log.error("Error inside sortList method"+e);
}
return returnVal;
}
});
}
else
{
usReleaseDateSortAsc = "Desc";
Collections.sort(carList, new Comparator<CarDataTransferObject>()
{
public int compare(CarDataTransferObject object1, CarDataTransferObject object2)
{
int returnVal = 0;
try
{
returnVal = sdf1.parse(object2.getManufacturedDate()).compareTo(sdf1.parse(object1.getManufacturedDate()));
}
catch (Exception e)
{
log.error("Error inside sortList method"+e);
}
return returnVal;
}
});
}
}
最佳答案
我很确定这是一个问题,因为 null
值(value)观。
看看你的compare()
方法:
int returnVal = 0;
try {
returnVal = sdf1.parse(object2.getManufacturedDate()).compareTo(sdf1.parse(object1.getManufacturedDate()));
} catch (Exception e) {
log.error("Error inside sortList method"+e);
}
return returnVal;
如果两者之一是 null
会发生什么?你会得到一个异常并返回 0。
然而,null
应该总是被认为大于或小于任何非空值。 Comparator
的要求结果必须是可传递的,即如果a < b
和 b < c
然后 a < c
.现在,如果其中之一是 null
(比方说 c
)然后你的代码会违反这一点,即它可能导致 a < b
, b = c
和 a = c
这显然违反了契约(Contract)。
因此您需要单独检查空值:
if(date1 == null ) {
if (date2 == null) {
return 0;
} else {
return /*either -1 or 1 depending on where nulls should end up*/
}
} else {
if (date2 == null) {
return /*either 1 or -1 depending on where nulls should end up*/
} else {
return date1.compareTo(date2); //this assumes successful parsing, I'll leave those details for you
}
}
关于java - 在java中对日期值进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52851969/