Set and HashSet : HashSet « Collections « Java Tutorial

  1. A Set represents a mathematical set.
  2. It is a Collection that, unlike List, does not allow duplicates.
  3. There must not be two elements of a Set, say e1 and e2, such that e1.equals(e2).
  4. The add method of Set returns false if you try to add a duplicate element.
import java.util.HashSet;
import java.util.Set;

public class MainClass {

  public static void main(String[] a) {
    Set set = new HashSet();
    if (set.add("Hello")) {
      System.out.println("addition successful");
    } else {
      System.out.println("addition failed");

addition failed
  1. HashSet allows at most one null element.
  2. HashSet is faster than other implementations of Set, TreeSet and LinkedHashSet.

9.19.1.Set and HashSet
9.19.2.Creating a HashSet
9.19.3.An easy way to initialize a set without manually adding each element
9.19.4.Adding Single Elements: the add() method
9.19.5.Adding Another Collection with the addAll() method: public boolean addAll(Collection c)
9.19.6.Removing All Elements: public void clear()
9.19.7.Removing Single Elements: public boolean remove(Object element)
9.19.8.Removing Another Collection: public boolean removeAll(Collection c)
9.19.9.Retaining Another Collection: public boolean retainAll(Collection c)
9.19.10.Fetching Elements: to work with all of the elements of the set
9.19.11.Checking for Existence: the contains() method reports if a specific element is within the set
9.19.12.the containsAll() method checks if a set contains another whole collection
9.19.13.To find out how many elements are in a set, use the size() method
9.19.14.Checking for no elements in the set: use the isEmpty() method instead
9.19.15.Copying and Cloning Sets: public Object clone()
9.19.16.HashSet implements the empty Serializable interface
9.19.17.Converting elements in a set to Array: public Object[] toArray()
9.19.18.public Object[] toArray(Object[] a)
9.19.19.The HashSet class defines equality through its equals() method: public boolean equals(Object o)
9.19.20.Find maximum element of HashSet
9.19.21.Find Minimum element of HashSet
9.19.22.Get Enumeration over HashSet
9.19.23.Get Synchronized Set from HashSet
9.19.24.Check if a particular element exists in HashSet
9.19.25.Copy all elements of HashSet to an Object Array
9.19.26.Get Size of HashSet
9.19.27.Iterate through elements of HashSet
9.19.28.Remove all elements from HashSet
9.19.29.Remove specified element from HashSet
9.19.30.Integer value set
9.19.31.Listing the Elements of a Collection(iterate over the elements of set or list)
9.19.32.Making a Collection Read-Only
9.19.33.Convert array to Set
9.19.34.Create unique lists of items?