HashSet : Java Glossary

HashSet
A wrapper around HashMap to implement the Set interface. Instead of put you used add. Instead of get you use contains.

You’d think HashSet would be a useful tool for arranging unique Objects. However, it is useless for that purpose because it will only tell you if an equivalent Object is already in the HashSet. It won’t divulge a reference to the canonical Object itself. To arrange uniqueness, you need a HashMap with key and value referencing the same canonical unique Object.

In other words,

HashSet.contains tells you if there is an Object in the HashSet Collection that matches yours, as measured by equals. It does not tell you if your Object is the exact same Object as the one in the Collection. Further, HashSet will not give you a reference to its Object. However, if you use HashMap instead, you can get a reference to the Collection’s Object.
Using HashSets Tips
Comparing HashSets for Duplicates Learning More
Initialisation Links

Using HashSets

Two other techniques for dealing with sets include EnumSet and BitSet.

Here is how you can initialise a HashSet in a single line.

Comparing HashSets for Duplicates

Initialisation

HashSet does not have a constructor that takes an array of initial values, but it does have one that takes a Collection. So you can initialise by using Arrays.asList to convert like this:

Tips

Alternatives

A HashSet is a fairly heavy duty solution. If you have only a few elements there are lighter weight ways of discovering if something belongs in a set.

Learning More

Oracle’s Javadoc on HashSet class : available:
Oracle’s Javadoc on Set interface : available:
Oracle’s Javadoc on Collections.unmodifiableSet : available:
Oracle’s Javadoc on Collections.emptySet : available:

CMP homejump to top

available on the web at:

http://mindprod.com/jgloss/hashset.html
  

optional Replicator mirror
of mindprod.com
on local hard disk J:

J:\mindprod\jgloss\hashset.html
logo
Please email your , letters to the editor, errors, omissions, typos, formatting errors, ambiguities, unclear wording, broken/redirected link reports, suggestions to improve this page or comments to Roedy Green : feedback email. If you want your message, your name or email kept confidential, not considered for public posting, please explicitly specify that. Unless you state otherwise, I will treat your message as a letter to the editor that I may or may not publish in the feedback section. After that, it will be too late to retract it. If you disagree with something I said, especially when sending an ad-hominem attack, a rant composed mainly of obscenities or a death threat, please quote the offending passage and cite the web page where you found it, tell me why you think it is wrong, and, if possible, provide some supporting evidence. I can’t very well fix erroneous or ambiguous text if I can’t find it.
Blog
IP:[65.110.21.43]
Your face IP:[107.22.156.205]
You are visitor number 31,472.