views:

364

answers:

3

Why does Java not provide functions to get at the key/value pairs in a HashSet like in Hashtable? It seems like a real pain to have to iterate over it every time you need to get at something. Or am I just a newb missing something?

+5  A: 

HashSet doesn't have key/value pairs. It is a Set of objects and you would use an implementer of Set to ensure that a collection of objects contained no duplicates.

Implementers of Map like HashMap have key/value pairs and provide a get(Object key) method to get the value associated with a key.

Brabster
Thanks, I think this is starting to make sense.
harley
Great. I remember I had the same confusion initially, I have found that I use Sets when I need to filter a bunch of objects down to unique objects only - in which case I usually then want to iterate over them and to stuff with them. I use Maps when I want to be able to look objects up by some value I'm using as a key.
Brabster
+2  A: 

Since a Set doesn't contain keys and values, there is no way such a view could be provided.

What would you consider to be the key and what would be the value in a Set?

Joachim Sauer
I guess I'm confused by the documentation: From Hashtable: "This class implements a hashtable, which maps keys to values. "From HashSet: "This class implements the Set interface, backed by a hash table (actually a HashMap instance). "Seeing how HashSet is a HashMap and HashMap is similar to Hashtable, why is there no way to get at the key/value pairs?If it is a question of uniqueness wouldn't overriding compareTo() be the way to go?
harley
The HashSet is _backed_ by a HashMap, which means that internally it uses a HashMap. That however does not mean that it exposes the HashMap.
Robert Munteanu
@Harley: As Robert said, the `HashMap` inside the `HashSet` is an implementation detail, it's not visible on the outside. Next: if you never **put in** a key/value pair, then what would you expect it to make visible?
Joachim Sauer
A: 

A Set don't have any key/value pairs, just (unique) values. As you already said you get these values via the Iterator or by returning an array with these values with the toArray() method.

Maybe you are looking for a List instead.

Progman