How can I make this unchecked method invocation checked?
This is driving me crazy. As it stands below the compiler complains that the method invocation is unchecked. If I add a type parameter getMax(Collection<Num> c) the compiler moans that it canno't find symbol method max(java.util.Collection<Num>).
Code:
public static Num getMax(Collection c){
return Collections.max(c);
}
The method prototype simply suggests that any type can be passed in that extends the type that the Collection is marked to hold. :confused:
Code:
public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll)
Re: How can I make this unchecked method invocation checked?
Yes, but Java's not smart enough to deduce the type, it seems. Try:
return Collections.max<Num>(c);
Re: How can I make this unchecked method invocation checked?
This is very confusing. The type param <Num> is necessary within or else im playing with unchecked method calls,
Code:
public static Num getMax(Collection<Num> c){
return Collections.max(c);
}
but then the compiler seems to not be able to find a version of
Code:
max(java.util.Collections<Num>)
Code:
return Collections.max<Num>(c);
Simple dosen't work. :(
Re: How can I make this unchecked method invocation checked?
Does your Num class implement Comparable?
Re: How can I make this unchecked method invocation checked?
Quote:
Posted by CornedBee
Does your Num class implement Comparable?
Now it does. :lol: Thanks for the help. :)
Code:
import java.util.Set;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
public class Max{
public static void main(String[] args){
Collection<Num> numl = new ArrayList<Num>();
numl.add(new Num("2"));
numl.add(new Num("6"));
numl.add(new Num("3"));
numl.add(new Num("1"));
numl.add(new Num("5"));
numl.add(new Num("4"));
System.out.print("Max element is " + getMax(numl).getNum());
}
public static Num getMax(Collection<Num> c){
return Collections.max(c);
}
}
class Num implements Comparable<Num>{
private String i;
public Num(String i){
this.i = i;
}
public int compareTo(Num num){
int x = i.compareTo(num.i);
return x;
}
public String getNum(){
return i;
}
}