• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Ron McLeod
  • paul wheaton
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
  • Himai Minh
Bartenders:

Type safety: Unchecked cast from Object to ArrayList

 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Ranch Hand
Posts: 37
  • Likes 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Daniel!
 
reply
    Bookmark Topic Watch Topic
  • New Topic