S
Scott W Gifford
I've got two generics-related warnings I can't figure out how to fix.
The first one is implementing a simple Comparator class for Object, to
sort an array that will mostly be Comparable objects, but may have
some non-Comparable ones thrown in, in which case I don't care about
the order of those. I've got this:
private final class CompHelper implements Comparator<Object> {
public int compare(Object o1, Object o2) {
if (o1 instanceof Comparable && o2 instanceof Comparable) {
return ((Comparable)o1).compareTo((Comparable)o2);
} else {
return o1.hashCode() - o2.hashCode();
}
}
}
which gives me:
Type safety: The method compareTo(Object) belongs to the raw type
Comparable. References to generic type Comparable<T> should be
parameterized
The second is taking a parameterized Class as a parameter, then
creating an instance of that class:
public Map<String,String> Example(Class<? extends Map> cacheClass) throws Exception {
return cacheClass.newInstance();
}
giving:
Type safety: The expression of type capture-of ? extends Map needs
unchecked conversion to conform to Map<String,String>
I've added @SuppressWarnings("unchecked") to these, but I'd rather fix
them The Right Way.
Any ideas?
Thanks!
---ScottG.
The first one is implementing a simple Comparator class for Object, to
sort an array that will mostly be Comparable objects, but may have
some non-Comparable ones thrown in, in which case I don't care about
the order of those. I've got this:
private final class CompHelper implements Comparator<Object> {
public int compare(Object o1, Object o2) {
if (o1 instanceof Comparable && o2 instanceof Comparable) {
return ((Comparable)o1).compareTo((Comparable)o2);
} else {
return o1.hashCode() - o2.hashCode();
}
}
}
which gives me:
Type safety: The method compareTo(Object) belongs to the raw type
Comparable. References to generic type Comparable<T> should be
parameterized
The second is taking a parameterized Class as a parameter, then
creating an instance of that class:
public Map<String,String> Example(Class<? extends Map> cacheClass) throws Exception {
return cacheClass.newInstance();
}
giving:
Type safety: The expression of type capture-of ? extends Map needs
unchecked conversion to conform to Map<String,String>
I've added @SuppressWarnings("unchecked") to these, but I'd rather fix
them The Right Way.
Any ideas?
Thanks!
---ScottG.