aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes HashSet and the iterator Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "HashSet and the iterator" Watch "HashSet and the iterator" New topic
Author

HashSet and the iterator

Lucas Smith
Ranch Hand

Joined: Apr 20, 2009
Posts: 804
    
    1

Why does HashSet implement Iterable?
HashSet is not ordered and a comparator object refers to the ordered collections - to iterate means to go through a collection / an array in ordered way. So what's up with HashSet?


SCJP6, SCWCD5, OCE:EJBD6.
BLOG: http://leakfromjavaheap.blogspot.com
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18113
    
  39

What does iteration has to do with being ordered? And if there isn't an iterator, how would you (easily) access all the elements in the set, so that you can do something with it?

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Lucas Smith
Ranch Hand

Joined: Apr 20, 2009
Posts: 804
    
    1

HashMap doesn't implement Iterable and I can deal with its elements
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18113
    
  39

Lukas Smith wrote:HashMap doesn't implement Iterable and I can deal with its elements


Yes... by getting a set (from the hashmap) first, and then iterating through it. If Set wasn't iterable, then how would you (easily) iterate through the keys or values?

Henry
Lucas Smith
Ranch Hand

Joined: Apr 20, 2009
Posts: 804
    
    1

OK, I understand you, thanks!
Samrat Som
Ranch Hand

Joined: Feb 04, 2009
Posts: 40
Hi Henry,

Can you elaborate it a bit. I just wanna know , even though HashMap is not iterable, we iterate it by creating a set out of it . Am I right? Please Clarify me in this context


SCJP 1.6
SCWCD 1.5 (Preparing...)
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 13872
    
  10

HashMap is not directly iterable, but it does provide methods such as keySet() and entrySet() which return Set objects that are iterable. There's also values(), which returns a collection of the values in the map (which is also iterable).

The designers of interface java.util.Map could have chosen to make it extend Iterable<Map.Entry<K, V>>, so that you could directly iterate over the map's entries. But they didn't do that.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: HashSet and the iterator
 
Similar Threads
K&B Book Error?
Difference beteween HashSet and LinkedHashSet.
Ordered and Sorted
Collection(Set), Using a HashSet
how can be retrieve from any collection into our own order?