Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

using Sets

 
aslika bahini
Ranch Hand
Posts: 111
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Hi There!






for(Object o:s)
System.out.print(o +" ");

may i know how the above code is represented in basic for loop?
there is no length attribute in set. instead, it has size()

for(declaration:expression)

expression must evaluate to the array to loop through. this could
be array variable or a method call that returns an array.
here 's' is not array. which is an set s = new Hashset();

how it works? correct me!



Thanks!
regards
samura




 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by samura babu:
...for(declaration:expression)

expression must evaluate to the array to loop through...

It does not need to be an array. The enhanced for statement can use either an array or any container that implements Iterable.

See JLS 14.14.2 The enhanced for statement.
 
dolly shah
Ranch Hand
Posts: 383
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are looking both the for loops differently. The basic for loop is for boolean (ba) that is declared as array. The enhanced for loop is for Set, because the type of collection(generic<> is not specified here, the things come out from Set is Object.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic