我在使用 Collections.min 时遇到 NoSuchElementException,我也在网站上阅读了其他相关问题,并了解到如果使用的列表或集合为空,则会出现此异常。但我已经检查了调试代码,列表有值,但我仍然收到异常。
public Date getNewDate(List<MyClass> list1){
Comparator<MyClass> startDate = new Comparator<MyClass>() {
@Override
public int compare(MyClass date1, MyClass date2) {
return date1.getStartDate().compareTo(date2.getStartDate());
}
};
return Collections.min(list1, startDate).getStartDate();
}
最佳答案
当您的第一个信息来源 javadoc 明确告诉您这一点时,为什么您需要阅读其他相关问题来了解这一点?
引用Collections.min()的javadoc :
Throws
NoSuchElementException
if the collection is empty.
因此,您的集合 (list1
) 为空。
如果您不相信,请 try catch 并增强错误消息:
try {
return Collections.min(list1, startDate).getStartDate();
} catch (NoSuchElementException e) {
throw new RuntimeException("Got NoSuchElementException but list size is " +
list.size() + " (list is: " + list + ")", e);
}
向我们显示执行此操作时生成的完整堆栈跟踪,以证明当您收到异常时列表不为空。
这还将向我们显示列表的内容,这是提供 a Minimal, Complete, and Verifiable example 的一部分.
关于java - NoSuchElementException 当 List 不为空时使用 Collections.min(List, Comparator) 时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36171288/