Java HashSetJava HashSet class is used to create a collection that uses a hash table for storage. It inherits the AbstractSet class and implements Set interface. The important points about Java HashSet class are:
Difference between List and SetA list can contain duplicate elements whereas Set contains unique elements only. Hierarchy of HashSet classThe HashSet class extends AbstractSet class which implements Set interface. The Set interface inherits Collection and Iterable interfaces in hierarchical order. HashSet class declarationLet's see the declaration for java.util.HashSet class. Constructors of Java HashSet class
Methods of Java HashSet classVarious methods of Java HashSet class are as follows:
Java HashSet ExampleLet's see a simple example of HashSet. Notice, the elements iterate in an unordered collection. Five One Four Two Three Java HashSet example ignoring duplicate elementsIn this example, we see that HashSet doesn't allow duplicate elements. Ajay Vijay Ravi Java HashSet example to remove elementsHere, we see different ways to remove an element. An initial list of elements: [Vijay, Ravi, Arun, Sumit] After invoking remove(object) method: [Vijay, Arun, Sumit] Updated List: [Vijay, Arun, Gaurav, Sumit, Ajay] After invoking removeAll() method: [Vijay, Arun, Sumit] After invoking removeIf() method: [Arun, Sumit] After invoking clear() method: [] Java HashSet from another CollectionVijay Ravi Gaurav Ajay Java HashSet Example: BookLet's see a HashSet example where we are adding books to set and printing all the books. Output: 101 Let us C Yashwant Kanetkar BPB 8 102 Data Communications & Networking Forouzan Mc Graw Hill 4 103 Operating System Galvin Wiley 6 You may also like: Working of HashSet in JavaNext TopicJava LinkedHashSet class |