PDA

View Full Version : Returning elements of a set


Touchstone57
03-04-2009, 08:58 PM
Probably a stupid question, but how do I return the elements of a set? I can seem to find no methods available for doing this...

Say for example I wanted to print out the name of an element in my set, returning an element at the specified index, how would I do it, a long these lines?

Set<SomethingHere> setName = new HashSet<SomethingHere>(ListHere);

//Though the get operation was not available
System.out.println(setName.get(1).getName());

Any help greatly appreciated, thanks.

Fou-Lu
03-04-2009, 09:13 PM
Are you sure a hashset is what you're looking to use? Methinks a hashtable is what you want, which is a typeof map. Set does not have a get method on it, but map does.

Touchstone57
03-04-2009, 09:30 PM
I wan't to be using a HashSet I think, to prevent duplicates (because I have many).

Fou-Lu
03-04-2009, 09:55 PM
I believe hashmap will prevent this. I'm pretty sure that it will overwrite the existing value stored in a hash if its given a hashkey. Hashkey is contracted to remain the same in any single object entity.
Only one way to find out, create a hashmap, create an object and store two identical instances of that object within the hashmap (but not two copies of the same object). Check the size, if its 1 it good, otherwise its using a doublehashing technique of some sorts or a secondary datacollection to store secondary data. Remember that the data should override the equals method and technically the hash method as well.