简体   繁体   中英

Problems with Java Generics with comparable

I'm trying to do a very simple class in order to return the min value of a collections. This is my code:

public class Min_Comparable <T extends Comparable<? super T>> {

    public  T min(Collection<? extends T> c){
        Iterator<? extends T> it = c.iterator();
        T min = it.next();
        while(it.hasNext()){
            if(min.compareTo(it.next()) > 0 ){
                min = it.next();
            }
        }
        return min;
    }
}

This is my main:

public class Main {

    public static void main(String[] args) {
        Min_Comparable test = new Min_Comparable();
        ArrayList<Integer> list = new ArrayList<Integer>();
        list.add(6);
        list.add(0);
        list.add(5);
        list.add(2);

        System.out.println(test.min(list));

    }
}

This is my errors:

Exception in thread "main" java.util.NoSuchElementException
    at java.util.ArrayList$Itr.next(ArrayList.java:854)
    at MidTerm.Min_Comparable.min(Min_Comparable.java:16)
    at MidTerm.Main.main(Main.java:20)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)

So my question is: very is the mistake? I have no error in the wildcards or generics, i think that everything is casting so what am i doing wrong?

You are using next twice, when hasNext has only been checked once. Hence the NoSuchElementException . Try this instead.

while(it.hasNext()){
    T next = it.next();     
    if(min.compareTo(next) > 0 ){
        min = next;
    }
}

You are calling next() twice

if(min.compareTo(it.next()) > 0 ){
            min = it.next();
 }

This advances the iterator twice. You want to only call next once and save it as to a variable

 T next = it.next();
 if(min.compareTo(next) > 0 ){
            min = next;
 }

如果您希望看到一个基于Guava的非常简单而强大的实现,请看一下这篇文章 :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM