gpt4 book ai didi

java - 在java中对日期值进行排序

转载 作者:行者123 更新时间:2023-11-29 08:26:10 25 4
gpt4 key购买 nike

我有一个 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 < bb < c然后 a < c .现在,如果其中之一是 null (比方说 c )然后你的代码会违反这一点,即它可能导致 a < b , b = ca = 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com