2

In a ServletContextListener, I set an attribute like this:

ArrayList<String> prefs = new ArrayList<String>();
...
...
sc.setAttribute("user-preferences", prefs);

I try to use the attribute in a JSP page like this:

ArrayList<String> prefs = (ArrayList<String>) config.getServletContext().getAttribute("user-preferences");

I get the following warning:

Type safety: Unchecked cast from Object to ArrayList

Can someone please tell me why I get this warning?

Thanks.

bdhar
  • 21,619
  • 17
  • 70
  • 86

1 Answers1

2

This warning is because ServletContext.getAttribute() does not support generics and the method signature of this method says the return object is Object. But, you are type casting it to ArrayList<String>.

ServletContext.getAttribute() API Reference

It's a standard Java warning, indicating that you are casting a non-generic type (Object) to a generic type (ArrayList).

In Java you can remove the warning by using an unchecked annotation.

Unchecked Warning Turtorial

Ramesh PVK
  • 15,200
  • 2
  • 46
  • 50
  • Thanks. I have replaced the `ArrayList` with a `String[]`. No warning now. Is this a good practice? – bdhar Feb 08 '12 at 07:41
  • 1
    Writing Java code in a JSP file instead of a normal Java class is [a bad practice in any way](http://stackoverflow.com/questions/3177733/how-to-avoid-java-code-in-jsp-files) :) – BalusC Feb 08 '12 at 12:58
  • 1
    Then how to replace those Java calls?, by using JSTL?. – will824 Nov 22 '12 at 20:01