Collection : HashSet Example


 

Collection : HashSet Example

This tutorial contains description of HashSet with example.

This tutorial contains description of HashSet with example.

Collection : HashSet Example

This tutorial contains description of HashSet with example.

HashSet  :

HashSet class extends AbstractSet class and implements the Set interface. It uses hash table for storage. It doest not assure you for order of elements and also not sure that order will remain constant over time. It does not allow duplicate value. HashSet does not provide any its own method but uses its super class and interface methods.

Methods : Following methods are used by HashSet -

add(Object o) - It adds specified element to the HashSet if it is not already present in set.

clear() - Its function to remove all the elements of hasSet.

clone() - It returns a shallow copy of your hashSet object.

contains(Object o) - Boolean type. It returns true if the specified element is presented in HashSet otherwise returns false.

isEmpty() - Boolean type. It returns true if your HashSet is empty.

iterator()- Iterator type. It returns an iterator over the elements in the HashSet.

remove(Object o) - Boolean type. It removes the element from the HashSet if it is presented otherwise returns false.

size() - It returns the number of elements in your HashSet.

Example : Here is HashSet() example -

package collection;

import java.util.HashSet;

class HashSetExample {
public static void main(String[] args) {
// Creating HashSet
HashSet hSet = new HashSet();

// Inserting elements
hSet.add(100);
hSet.add(200);
hSet.add('H');
hSet.add("Roseindia");
hSet.add("Hello");

System.out.println("Size of HaseSet : " + hSet.size());
System.out.println("Content of HashSet : " + hSet);

// Removing elements
hSet.remove(100);
hSet.remove(444);
System.out.println("Size of HaseSet : " + hSet.size());
System.out.println("Content of HashSet : " + hSet);

System.out.println("hSet.contains('H') : " + hSet.contains('H'));
}
}

Description : In this example we are using HashSet to storing elements. You can create HashSet as -
 HashSet hSet = new HashSet();
add()
method is used here to add elements. size() method calculating the elements of HashSet and then displaying its elements.
For deleting elements you can use remove() method.

Output :

Size of HaseSet : 5
Content of HashSet : [100, 200, H, Hello, Roseindia]
Size of HaseSet : 4
Content of HashSet : [200, H, Hello, Roseindia]
hSet.contains('H') : true

Ads