0% found this document useful (0 votes)
60 views

HashSet in Java

This document discusses how to use a HashSet in Java. It shows how to add elements to the set, check the size, search for elements, remove elements, print all elements, iterate through the set using an iterator, and check if the set is empty. The HashSet does not maintain insertion order of elements and does not allow duplicate values.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
60 views

HashSet in Java

This document discusses how to use a HashSet in Java. It shows how to add elements to the set, check the size, search for elements, remove elements, print all elements, iterate through the set using an iterator, and check if the set is empty. The HashSet does not maintain insertion order of elements and does not allow duplicate values.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

HashSet in Java

import java.util.HashSet;
import java.util.Iterator;

public class Hashing {


public static void main(String args[]) {
HashSet<Integer> set = new HashSet<>();

//Add
set.add(1);
set.add(2);
set.add(3);
set.add(1);

//Size
System.out.println("size of set is : " + set.size());

//Search
if(set.contains(1)) {
System.out.println("present");
}

if(!set.contains(6)) {
System.out.println("absent");
}

//Delete
set.remove(1);
if(!set.contains(1)) {
System.out.println("absent");
}

//Print all elements


System.out.println(set);

//Iteration - HashSet does not have an order


set.add(0);
Iterator it = set.iterator();
while (it.hasNext()) {
System.out.print(it.next() + ", ");
}
System.out.println();

//isEmpty
if(!set.isEmpty()) {
System.out.println("set is not empty");
}
}
}

You might also like