Search code examples
javacomparable

Java: Compareable<List<T extends Compareable<T>>>


Is there any Compareable<Collection<T extends Compareable<T>>> implementation in Java (which behaves as C++'s std::list<T>::operator<() or std::set<T>::operator<())?


Edit: Comparator would make more sense...


Solution

  • Not that I am aware of, but it shouldn't be too difficult to write.

    compareTo(Collection<T> other) {
        Iterator<T> i1 = this.iterator();
        Iterator<T> i2 = other.iterator();
        while(i1.hasNext() && i2.hasNext()) {
            int c = i1.next().compareTo(i2.next());
            if(c != 0) {
                return c;
            }
        }
        if(i1.hasNext()){
            return 1;
        } else if(i2.hasNext()) {
            return -1;
        } else {
            return 0;
        }
    }