File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

what's up with HashSet?

 
Randall Twede
Ranch Hand
Posts: 4353
2
Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i don't see any get methods at all!!!
i guess you use the iterator() method.
i never learned using iterators. could someone show me how? here is the offending code(you might notice i am more used to using arrays):


i am just trying to get the sum of all the ints in the HashSet
 
Pete Nelson
Ranch Hand
Posts: 147
Debian Eclipse IDE Tomcat Server
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A HashSet is a specific implementation of java.util.Set that is backed by a HashMap. Note that it doesn't implement java.util.Map (it "has a" Map, not "is a" Map). Strait from the javadoc, a Set "makes no guarantees as to the iteration order of the set", which is why trying to retrieve an object at a particular index will not work.

Is a Set truly what you are looking for here? Sets do not allow duplicates, so you would only get the sum of UNIQUE integers if you are using a Set.
 
Randall Twede
Ranch Hand
Posts: 4353
2
Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yes, no duplicates is why i chose it. i found an article that not only shows how to use iterators, but also the for-each statement. that should make it very easy.

if you ask me the java language is improving
i still have problems with this problem but the HashSet is not one now
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Note that you should always use a foreach loop or an explicit Iterator to iterate any collection. Never use get(i).

i never learned using iterators. could someone show me how?

java iterator tutorial
http://docs.oracle.com/javase/tutorial/collections/index.html
 
Xavier Figueroa
Greenhorn
Posts: 6
Java Netbeans IDE Spring
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You need something like:


or use an enhanced for loop
 
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
With the new for-loop syntax you don't need to use an Iterator explicitly. You can also make use of auto(un)boxing, which means you don't need to call intValue() on the Integer object. You could write it like this:
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic