How do I address unchecked cast warnings?

1.0K    Asked by asutos_8102 in Devops , Asked on Jun 27, 2021

 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?

Answered by Amy Avery

SuppressWarning

@SuppressWarnings instruct the compiler to ignore or suppress the specified program warning in interpreted elements and all program elements inside that element, as an example, if a class is interpreted 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 the most popular samples of @SuppressWarnings annotation. Also if you limit the scope, this way it won’t even affect the entire method.

SuppressWarnings signifies the potential programming error or mistake, so it's recommended to use them slenderly and instead attempt to solve the 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.



Your Answer

Interviews

Parent Categories