The intention behind using generics is to avoid surprises for the JVM.
i.e., You should use generics to avoid runtime(class cast) exceptions.
So in this case you are ought to get this warning in eclipse. There is
nothing wrong in type casting as well, as you are sure that the
attribute you are getting is what you have set before. Well, you can
avoid this warning by implementing Map interface and having something
like this:-
class ItemInfoMap extends HashMap<String,ItemInfo> implements
Map<String,ItemInfo>{
public ItemInfoMap put(String key, ItemInfo value) {
return super.put(key, value);
}
public ItemInfoMap get(String key) {
return super.get(key, value);
}
}
Now Use ItemInfoMap instead of Map :-)
ItemInfoMap userCart = (ItemInfoMap)
session.getAttribute("userCart");
Hope this helps!
Thanks!
Please do not top-post. Use trim-and-inline posting.
> The intention behind using generics is to avoid surprises for the JVM.
It's to avoid surprises for the programmer, I should say.
> i.e., You should use generics to avoid runtime(class cast) exceptions.
> Well, you can
> avoid this warning by implementing Map interface and having something
Not really a good idea.
"JTL.zheng" wrote:
>> Hashtable<String, ItemInfo> userCart = (Hashtable<String, ItemInfo>)
>> session.getAttribute("userCart");
Do you need the synchronization that Hashtable provides? Even if you do,
making a synchronizedMap off HashMap is likely a better choice, if not just
use HashMap.
>> I am using Eclipse
This is a Java issue, not an Eclipse issue.
>> It get a warning:
>> Type safety: The cast from Object to Hashtable<String,ItemInfo> is
[quoted text clipped - 10 lines]
>>
>> what's wrong with this sentence?
Welcome to type erasure. Generic casts just don't work unless you suppress
the warning. At run time there is no generic information, so the cast is
"raw" anyway. An attempt to cast a raw type but assign to a generic type
makes the compiler cough. It's what people don't like about Java generics,
and there are proposals afoot to use "reified generics", i.e., generics that
work at run time.
>> how can I fix it?
Instead of implementing the cart as a Map, implement it as a custom type that
contains a Map. (Make sure it implements java.io.Serializable.) Change the
session object retrieval to
ShoppingCart userCart = (ShoppingCart) session.getAttribute( "userCart" );

Signature
Lew