Casting a hashtable (using generics)
I have a hashtable saved to a file and I need to recreate the object in memory, so I'm using something like this:
obj = objIn.readObject();
if (objinstanceof Hashtable)
{
myHashtable = (Hashtable<K, V>) obj;
}
When I compile, a warning says that I'm using a unchecked / unsafe operation. If I compile with -Xlint, it says that the "obj" (in the cast line above) should be a Hashtable<K, V>, but it's just a Hashtable.
I'm new to java and would like to know if there's anyway to make this cast without generate any warnings.
Thanks in advance.
You did this:
obj = objIn.readObject();
if (obj instanceof Hashtable)
{
myHashtable = (Hashtable<K, V>) obj;
but i think you have to it like this:
obj = objIn.readObject();
if (Hashtable<K, V> obj instanceof Hashtable)
{
myHashtable = (Hashtable<K, V>) obj;
I'm not sure but i think that's logical.
Succes,
Jasper
I'm not sure about Xlint. But the compiler will show a warning, because you cannot cast to a parameterized type because of erasure at runtime (and the cast is a runtime operation). Hence, it does not matter if you cast to Hashtable or Hashtable<K, V>. That's all the compiler tells you and the only thing to "get rid" of the warning is to add a @SuppressWarning("unchecked") if you are sure, it is having K and V as type.
If you are going to be deserializing objects from a file, there is no way the compiler can guarantee at compile time that the objects will be of the desired class. So there is no way you can avoid warning messages (apart from telling the compiler not to warn you, as stefan.schulz says).