• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Liutauras Vilda
  • Paul Clapham
Sheriffs:
  • paul wheaton
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Piet Souris
Bartenders:
  • Mike London

Help Me Downcast

 
Ranch Hand
Posts: 361
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

The above works fine. Now if I wish to change the for loop just a bit like:
for(String s String)l)
System.out.println(s);
It doesnt work. The problem is in the for loop How can I downcast the List's values which are Objects to Strings to get my proposed for loop to work?
 
Ranch Hand
Posts: 809
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
One option is cast o in for loop like this...



or you can directly assign aList in generic type List<? extends String> instead of List<? extends Object>. In that case, your for loop will change to...




Naseem
 
Amit Batra
Ranch Hand
Posts: 361
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Naseem. I was trying to cast in the for each loop itself but I guess thats just not a possibillity and must be done in the body of the loop.
 
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
may be you can use List<? extends String> l = aList;
instead of List<? extends Object> l = aList;

 
reply
    Bookmark Topic Watch Topic
  • New Topic