Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

foreach

 
Pradeep Sadashivamurthy
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 13459
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch! Please UseCodeTags!
 
Darryl Burke
Bartender
Posts: 5125
11
Java Netbeans IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your variable result is of type List<String>, not Object[]
 
David O'Meara
Rancher
Posts: 13459
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
agreed
 
Rob Spoor
Sheriff
Pie
Posts: 20511
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
K Abhijit
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Rob Spoor
Sheriff
Pie
Posts: 20511
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If the method returns a List<String> but the contents are actually Object[] then that method is severely broken.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic