0

This method is supposed to find the smallest value in a Collection that is greater than the key. I keep getting a java.lang.UnsupportedOperationException, and I can't figure out how to fix it. Thanks in advance for any help.

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;
}
Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276
me123
  • 43
  • 6

1 Answers1

6

Most likely you are trying to modify a collection which is unmodifiable.

I suggest you change the method to not modify the collection. (Also I suggest you read the stack trace to understand what it means)

Something like this

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;
}
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130