0

该方法应该在集合中找到大于键的最小值。我不断收到 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;
}
4

1 回答 1

6

您很可能正在尝试修改不可修改的集合。

我建议您更改方法以不修改集合。(另外我建议您阅读堆栈跟踪以了解其含义)

像这样的东西

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;
}
于 2015-02-05T21:26:38.410 回答