This week's book giveaway is in the Agile and other Processes forum.
We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line!
See this thread for details.
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
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Beginning Java
Reply 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://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: Type safety: Unchecked cast from Object to ArrayList
 
Similar Threads
warning Type Safety while assign from object to serealizable Arralist
generics compiler warning
Unchecked cast from Object to searilizable ArrayList
Unchecked cast
Type Casting Generics