This week's book giveaway is in the Big Data forum.
We're giving away four copies of Elasticsearch in Action and have Radu Gheorghe & Matthew Lee Hinman on-line!
See this thread for details.
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

Win a copy of Elasticsearch in Action this week in the Big Data forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "foreach" Watch "foreach" New topic


Pradeep Sadashivamurthy

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



Where as the following code works fine:

Please help me in understanding this.
David O'Meara

Joined: Mar 06, 2001
Posts: 13459

Welcome to the Ranch! Please UseCodeTags!
Darryl Burke

Joined: May 03, 2008
Posts: 4758

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

Joined: Mar 06, 2001
Posts: 13459

Rob Spoor

Joined: Oct 27, 2005
Posts: 19908

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.

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[]);

List<String> result = sess.createQuery(sql).list();
Object [] obj = null;
for(Iterator it = result.iterator();it.hasNext(); ){
obj = (Object[]);
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

Joined: Oct 27, 2005
Posts: 19908

If the method returns a List<String> but the contents are actually Object[] then that method is severely broken.
rocket mass heater kickstarter
subject: foreach