Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Type safety: Unchecked cast from Object to ArrayList

 
Bob Hysell
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 37
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Daniel!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic