3
I’m creating a class that through that works similar to Xpath.
The function works perfectly, the problem is that in this part of the line (HashMap<String, Object>) test.get("test-map");
, "eclipse" shows the following warning:
Type Safety: Unchecked cast from Object to Hashmap
I believe it’s my fault, the way I’m working may be wrong.
How can I solve?
HashMap<String, Object> test = new HashMap<String, Object>();
test.put("test-string", "abc");
boolean isNull = test.get("test-map")==null;
if(isNull==false){
HashMap<String, Object> map1 = (HashMap<String, Object>) test.get("test-map");
System.out.println(map1);
isNull = map1==null;
}
if(isNull){
test.put("test-map", new HashMap<String, Object>());
}
String map2 = (String) test.get("test-string");
System.out.println(map2);
So I’ve done this, but I don’t believe this is the best.
– Guilherme Nascimento
You have 2 alternatives, either you change your map to instead of being string to Object to be string to hashmap<...> (which may not be possible) or you guarantee via programming logic that at that moment you are giving the cast what you have there is actually a hashmap<...>. And if via logic is guaranteed, you can suppress the Warning.
– C. E. Gesser
I agree, but what I need to know is: is this really the best way to do this? I refer to my code.
– Guilherme Nascimento
I’d say you’re the only one. By a choice of java design, information about Hashmap generic arguments (and any class that has type arguments) is not preserved at runtime. The execution environment will know that it is a Hashmap, but will not know what it is. So it will always give Warning when you force a cast to a type with Generics. There is an option to declare the variable as Hashmap<? ,? >, which is safe and does not give warnings, but prevents you from using the map.
– C. E. Gesser
You can change your logic, so that besides the Object in the map you also store an identifier of what type of object was saved, it can be an Enum. This way, when removing the object you can make a check and be sure of the type of the object. And so you can place the Warning deletion annotation knowing that you are doing everything possible.
– C. E. Gesser
Just to conclude, my code is good, or I should use
instanceof
?– Guilherme Nascimento
instanceof
It won’t solve the Warning problem, so it’s useless to use it.– Philippe Gioseffi
With the
instanceof
you can at most test whether the content of the object is aHashMap
, but you won’t be able to tell the difference between aHashMap<A,B>
and aHashMap<C,D>
, because that information is lost at runtime. If you want to be absolutely sure what you have in the map you will need to store this information, for example as aenum
, as I said. But this ties more architecture, for every new type you want to put you will have to add a new entry in Enum.– C. E. Gesser