Reputation: 531
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?
Upvotes: 0
Views: 62
Reputation: 1295
Have a look at this post if you would like to see a really simple & powerful implementation based on Guava :)
Upvotes: 1
Reputation: 37645
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;
}
}
Upvotes: 5
Reputation: 31648
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;
}
Upvotes: 1