0

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?

3
  • 3
    This is a statement, not a question. Commented Oct 26, 2015 at 15:27
  • 5
    The main problem I can see is that you're using next twice for each hasNext. Commented Oct 26, 2015 at 15:28
  • @PaulBoddington should be right ;) Commented Oct 26, 2015 at 15:30

3 Answers 3

5

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;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

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;
 }

Comments

1

Have a look at this post if you would like to see a really simple & powerful implementation based on Guava :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.