aspose file tools*
The moose likes Java in General and the fly likes foreach Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "foreach" Watch "foreach" New topic
Author

foreach

Pradeep Sadashivamurthy
Greenhorn

Joined: Sep 17, 2010
Posts: 6
I'm facing syntax error in foreach loop. Where as the same logic works in for loop.

FOR LOOP:

FOREACH LOOP:

Where as the following code works fine:

Please help me in understanding this.
Thanks
David O'Meara
Rancher

Joined: Mar 06, 2001
Posts: 13459

Welcome to the Ranch! Please UseCodeTags!
Darryl Burke
Bartender

Joined: May 03, 2008
Posts: 4658
    
    5

Your variable result is of type List<String>, not Object[]


luck, db
There are no new questions, but there may be new answers.
David O'Meara
Rancher

Joined: Mar 06, 2001
Posts: 13459

agreed
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19762
    
  20

Your code will eventually throw a ClassCastException. Either the contents of the List are indeed String and the cast to Object[] will fail, or the contents are Object[] and a possible future usage as String will fail.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
K Abhijit
Ranch Hand

Joined: Mar 03, 2008
Posts: 88
few things initially...
actually from the declaration of the Collection results, it looks to like the data returned by sess.createQuery(sql).list() as simple String List but actual
implementation indicates it a List of Object arrays...
this is causing confusion..and a worthy candidate for ClassCastException

secondly it sucks in first case is When you say:

List<String> result = sess.createQuery(sql).list();
for(Object [] obj : result) // SYNTAX ERROR in this line

this is because actual code generated is
Object [] obj = result.get(someInt); ie. Object [] object = String //// error
Since result is been declared as List<String> it cries....

where as in later case you say it works because: you are explicitly typecasting the object : obj = (Object[])it.next();

List<String> result = sess.createQuery(sql).list();
Object [] obj = null;
for(Iterator it = result.iterator();it.hasNext(); ){
obj = (Object[])it.next();
for(Object s: obj){

Remove Typecasting, it would flag Error:

I've not tried this example but would so and update my findings


“The difference between 'involvement' and 'commitment' is like an eggs-and-ham breakfast: the chicken was 'involved' - the pig was 'committed'.”
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19762
    
  20

If the method returns a List<String> but the contents are actually Object[] then that method is severely broken.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: foreach