File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

HashSet and the iterator

 
Lucas Smith
Ranch Hand
Posts: 808
1
Android Eclipse IDE Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Henry Wong
author
Marshal
Pie
Posts: 20836
75
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Lucas Smith
Ranch Hand
Posts: 808
1
Android Eclipse IDE Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
HashMap doesn't implement Iterable and I can deal with its elements
 
Henry Wong
author
Marshal
Pie
Posts: 20836
75
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 808
1
Android Eclipse IDE Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
OK, I understand you, thanks!
 
Samrat Som
Ranch Hand
Posts: 40
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Pie
Posts: 15150
31
Android IntelliJ IDE Java Scala Spring
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic