Explore Courses Blog Tutorials Interview Questions
+12 votes
in Java by (1.2k points)

I use Eclipse for java, this is the error is got.

Type safety: Unchecked cast from Object to HashMap

Now there is another that I get from a call to an API that I have no control over returns

HashMap<String, String> getItems(javax.servlet.http.HttpSession session) {
  HashMap<String, String> theHash = (HashMap<String, String>)session.getAttribute("attributeKey");
  return theHash;

I would like to avoid Eclipse warnings, if possible. I read somewhere I could use SupressWarning to do it, what is it and how to use it?

2 Answers

+13 votes
by (13.2k points)


@SuppressWarnings instruct the compiler to ignore or suppress the specified compiler warning in annotated element and all program elements inside that element, as an example, if a class is annotated to suppress a particular warning, then a warning generated during the methodology inside that class will also be suppressed.

@SuppressWarnings("unchecked") and @SuppressWarnings("serial")  are two of most popular samples of @SuppressWarnings annotation. Also if you limit the scope, this way it won’t even affect the entire method.

SuppressWarnings indicates the potential programming error or mistake, so it's recommended to use them slenderly and instead attempt to solve actual problem which is triggering that warning. But there are situations when you are absolutely sure that things won't go wrong, you can use @SuppressWarnings to suppress those warnings.

+2 votes
by (108k points)

You don't have to perform the unchecked cast.

If it's certainly necessary, then at least try to limit the scope of the @SuppressWarningsannotation. According to its Javadocs, it can run on local variables; this way, it doesn't even affect the entire method.



Map<String, String> myMap = (Map<String, String>) deserializeMap();

There is no way to decide whether the Map really should have the generic parameters <String, String>. You must know what the parameters should be (or you'll find out when you get a ClassCastException). This is why the code produces a warning because the compiler can't possibly know whether is safe.

Browse Categories