aspose file tools*
The moose likes Beginning Java and the fly likes Type safety: Unchecked cast from Object to ArrayList Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Type safety: Unchecked cast from Object to ArrayList" Watch "Type safety: Unchecked cast from Object to ArrayList" New topic
Author

Type safety: Unchecked cast from Object to ArrayList

Bob Hysell
Greenhorn

Joined: Apr 14, 2011
Posts: 7
The statement
(ArrayList<ProjectBean>)(session.getAttribute("currentProjectList"));
yields the warning
Type safety: Unchecked cast from Object to ArrayList<ProjectBean>

Am I doing something wrong? The code works, it just generates a warning. How do I 'check' my cast to avoid the warning?
Daniel Marti
Ranch Hand

Joined: Jun 08, 2011
Posts: 37
A cast is checked at run time, but the problem is that at run time an ArrayList<ProjectBean> is no different than an ArrayList<Foo> (check this for more info). That is why the compiler is warning you that, while it will allow the cast, it cannot guarantee that you are indeed casting the correct type of Object. If the return of the getAttribute method is not a ArrayList<ProjectBeans> your method will launch a ClassCastException.
To make your code more robust i would check if the return from getAttribue is an instance of ArrayList<ProjectBeans>.Edit:Disregard this! Type erasure will make this void too! I shall warn you that probably you will still see the warning, if you get tired of seeing it just use a @SuppressWarnings("unchecked"). Although i don't like supressing warnings, in this case i feel it is appropriate.
And remember to catch the ClassCastException and deal with it accordingly.
Bob Hysell
Greenhorn

Joined: Apr 14, 2011
Posts: 7
Thanks Daniel!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Type safety: Unchecked cast from Object to ArrayList