Java shows "Type safety: Unchecked cast from Object to HashMap"

2

I'm creating a class that through which 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"); , the "eclipse" shows the following warning:

  

Type security: Unchecked cast from Object to HashMap

I believe it is a failure of mine, the way I am working may be wrong.

How can I resolve?

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);
    
asked by anonymous 30.01.2014 / 17:44

3 answers

2

This is a standard Java warning when casting generics .

In Eclipse, you can remove the warning by noting the variable declaration with:

@SuppressWarnings("unchecked")
HashMap<String, Object> map1 = (HashMap<String, Object>) test.get("test-map");

This warning happens because the compiler always guarantees that code using generics will not give ClassCastException . But since you're converting from a Object , that he has no way of knowing what it is, he gives this warning saying he does not guarantee it.

    
30.01.2014 / 17:54
0

Apply the following annotation in your method:

@SuppressWarnings("unchecked")

In this way eclipse will not signal this warning.

    
30.01.2014 / 18:37
-1

Eclipse throws this warning because you are casting without testing the object type. to avoid this, you could do the following:

if(test.get("test_map") instanceof HashMap<String, Object>){
    HashMap<String, Object> map1 = (HashMap<String, Object>) test.get("test-map");
}
...
    
30.01.2014 / 17:50