File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes what's up with HashSet? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "what Watch "what New topic

what's up with HashSet?

Randall Twede
Ranch Hand

Joined: Oct 21, 2000
Posts: 4351

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

Visit my download page
Pete Nelson
Ranch Hand

Joined: Aug 30, 2010
Posts: 147

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.

In preparing for battle I have always found that plans are useless, but planning is indispensable. -- Dwight D. Eisenhower
Randall Twede
Ranch Hand

Joined: Oct 21, 2000
Posts: 4351

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

Joined: Jan 03, 2004
Posts: 6109

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
Xavier Figueroa

Joined: Apr 13, 2012
Posts: 6

You need something like:

or use an enhanced for loop
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15081

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:

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
I agree. Here's the link:
subject: what's up with HashSet?
It's not a secret anymore!