Sunday, June 3, 2018

Set, HashSet in Java with Example

Set:- It is the child interface of collection.If we want to represent a group of individual object as a single entity where duplicate are not allowed and insertion order not required then we should go for Set interface.
- Basically Set is implemented by HashSet, LinkedSet or TreeSet.

Set has different methods which are following:-

add()- Add objects in the collection.

clear()- Remove all objects from the collection.

size()- It is used to return the no. of elements in the Set.

contains()- Return true if specified object present in the Set.

isEmpty()- Return true if the collection has no elements.

remove()- Remove a specified object from the collection.

iterator()- It is used for iterating the object from the Set.



HashSet:- HashSet class used to create a collection. It implements the Set interface and extends AbstractSet class. Objects that you insert in HashSet are not guaranteed to be inserted in same order. Null elements are allowed in HashSet.




Sample Program of HashSet:-



import java.util.HashSet;

public class HashSetDemo {
     
      public static void main(String[] args) {
           
           
            HashSet <String> hs = new HashSet <String>();
           
            hs.add("India");
            hs.add("Australia");
            hs.add("US");
            hs.add("Australia");
           
            //printing Hashset
            System.out.println("List of hash set:" + hs);
            System.out.println("List contains india or not:" + hs.contains("India"));
           
            //removing element
            hs.remove("India");
           
            //printing Hashset
            System.out.println("List of hash set after removing element:" + hs);
            System.out.println("Check hashset is empty or not:" + hs.isEmpty());
           
            //size of Hash Set
            System.out.println("No. of elements in HashSet:" + hs.size());
           
           
           
           
           
           
      }

}



Output:  



List of hash set:[Australia, US, India]
List contains india or not:true
List of hash set after removing element:[Australia, US]
Check hashset is empty or not:false
No. of elements in HashSet:2




                                          LinkedHashSet Class in Java with Example





No comments:

Post a Comment