此方法应该找到集合中大于键的最小值。我不断收到 java.lang.UnsupportedOperationException,并且不知道如何修复它。预先感谢您的任何帮助。
public static <T> T ceiling(Collection<T> c, T key, Comparator<T> comp) {
T ceiling = null;
if (c == null || comp == null) {
throw new IllegalArgumentException();
}
else if (c.size() == 0) {
throw new NoSuchElementException();
}
else {
Iterator<T> itr = c.iterator();
while (itr.hasNext()) {
if (comp.compare(itr.next(), key) < 0) {
itr.remove();
}
}
}
if (c.size() == 0) {
throw new NoSuchElementException();
}
else {
Iterator<T> itr2 = c.iterator();
ceiling = itr2.next();
while (itr2.hasNext()) {
T temp2 = itr2.next();
if (comp.compare(temp2, ceiling) < 0) {
ceiling = temp2;
}
}
}
return ceiling;
}
最佳答案
您很可能正在尝试修改不可修改的集合。
我建议你改一下方法,不要修改集合。 (我还建议您阅读堆栈跟踪以了解其含义)
类似这样的事情
public static <T> T ceiling(Collection<T> c, T key, Comparator<T> comp) {
if (c == null || comp == null)
throw new NullPointerException();
T ret = null;
for (T t : c)
if (comp.compare(t, key)>=0 && (ret==null || comp.compare(t, ret)<0))
ret = t;
return ret;
}
关于java - 修复 java.lang.UnsupportedOperationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28354300/