Re: What's wrong with this sentence?
- From: Zig <none@xxxxxxxxxxx>
- Date: Wed, 31 Oct 2007 16:36:55 -0400
On Wed, 31 Oct 2007 04:17:29 -0400, JTL.zheng <jtl.zheng@xxxxxxxxx> wrote:
Hashtable<String, ItemInfo> userCart = (Hashtable<String, ItemInfo>)
session.getAttribute("userCart");
I am using Eclipse
It get a warning:
Type safety: The cast from Object to Hashtable<String,ItemInfo> is
actually checking against the erased type
Hashtable
Ultimately, generics are erased, and this compiles down to
Hashtable userCart = (Hashtable) session.getAttribute("userCart");
You get the warning, since the runtime will only cast your "session.getAttribute" to Hashtable, and can not verify the contents of the table. Thus, a subsequent call to
ItemInfo info=userCart.getValue("somevalue");
*could* spuriously throw a ClassCastException (since the cast to ItemInfo is automatically generated by the compiler).
Hashtable<String, ItemInfo> userCart = (Hashtable)
session.getAttribute("userCart");
still get a warning too:
Type safety: The expression of type Hashtable needs unchecked
conversion to conform to
Hashtable<String,ItemInfo>
what's wrong with this sentence?
how can I fix it?
Some other posters have commented on using a Map instead of Hashtable. It would be a good idea, when map is initially created, to use Collections.checkedMap - which will ensure that the contents are what you expect.
Map<String, ItemInfo> cart=Collections.checkedMap(
Collections.synchronizedMap(new HashMap()),
String.class,
ItemInfo.class));
Now, you can safely assume that the contents of your map are always String, ItemInfo. The compiler will still generate the same warning, which you can now safely turn off by decorating the calling method with
@SuppressWarnings("unchecked")
Note that this turns off all unchecked cast warnings in that method, so do make sure that you have taken reasonable precautions to externally protect your data before turning off the warning.
HTH,
-Zig
.
- References:
- What's wrong with this sentence?
- From: JTL.zheng
- What's wrong with this sentence?
- Prev by Date: Re: Great SWT Program
- Next by Date: Re: Scheduled task using timer
- Previous by thread: Re: What's wrong with this sentence?
- Next by thread: memory management
- Index(es):
Relevant Pages
|