aspose file tools*
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
Author

what's up with HashSet?

Randall Twede
Ranch Hand

Joined: Oct 21, 2000
Posts: 4347
    
    2

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


SCJP
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.


OCPJP
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: 4347
    
    2

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

Joined: Jan 03, 2004
Posts: 6109
    
    6

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

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: 14157
    
  19

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 7 API documentation
Scala Notes - My blog about Scala
 
 
subject: what's up with HashSet?