Generic warning .....
Hi ,
Here my code gives unchecked warning .
Can any one solve this warning ?
Please urgent !
Here my code :
import java.util.HashMap;
public class DataMap<K, V> extends HashMap<K, V>
{
public V put(K key, V value)
{
if(key == null || value == null) return null;
if(key.getClass() == String.class)
{
key = (K)(key.toString().replace("'", "''"));
}
if(value.getClass() == String.class)
{
value = (V)(value.toString().replace("'", "''"));
}
return super.put(key, value);
}
}
Thanks........
[645 byte] By [
p.v.k.k] at [2007-11-26 12:15:58]

# 2
thanks for your response .
import java.util.HashMap;
public class DataMap<K, V> extends HashMap<K, V>
{
public V put(K key, V value)
{
if(key == null || value == null) return null;
if(key.getClass() == String.class)
{
key = (K)(key.toString().replace("'", "''"));
}
if(value.getClass() == String.class)
{
value = (V)(value.toString().replace("'", "''"));
}
return super.put(key, value);
}
}
my code gives the following warnings :
warning: [unchecked] unchecked cast
found: java.lang.String
required: K
key = (K)(key.toString().replace("'", "''"));
warning: [unchecked] unchecked cast
found: java.lang.String
required: V
value = (V)(value.toString().replace("'", "''"));
2 warnings
# 4
> please any one help me .....
So you want a Map which can only contain Strings, right?
Try it like this:
public class StringMap {
private Map<String, String> map;
// ...
public String put(String key, String value) {
// ...
}
}
# 5
> please any one help me .....
Sorry, but I just can't find out what
> key = (K)(key.toString().replace("'", "''"));
Is supposed to do, neither the cast nor the replace. Hence I can't tell you how to fix it.
edit: now with code tags, I can see. :p
# 8
Sometimes you have to live with these warnings, that's why they are warnings, not errors.
Since the type of V isn't known at compile time the compiler thinks it's unsafe to convert String to it. This conversion, at run time, actually doesn't do anything and it can't check that String fits the V class because of "erasure", i.e. the actual type isn't known at run time. In fact you know it's safe because the instanceof String couldn't be true if it weren't.
What you can do is to to include the Class objects of V and K as fields in your class, then you can use the Class.cast() method to do type conversion "safely". However it's probably not worth doing here. You can live with the warnings. When you get one of these warning you should think about why it happens and make sure what you're doing is actually safe.
for a start compile with the -Xlint:unchecked flag on the compiler command, that will give you details.
"value.getClass() == String.class" is horrible, by the way, use "value instanceof String".