Home > Java > javaTutorial > body text

HashSet in Java

WBOY
Release: 2024-08-30 16:20:45
Original
886 people have browsed it

The set interface is implemented by the HashSet class, which has a hash table as backup and is an instance of HashMap. Still, this class doesn’t guarantee on the order of the elements with time. A null element is permitted by this HashSet class providing time performance for operations like remove, add, etc. With the assumption that elements are dispersed among the buckets by the hash function.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Syntax

public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable, Serializable
Copy after login

Constructors in Java HashSet

The java HashSet class consists of several constructors. They are:

  • HashSet(): A default HashSet can be constructed using this constructor HashSet().
  • HashSet(int capacity): The capacity of the hashset can be initialized to the capacity of the given integer using this constructor HashSet(int capacity). As we go on adding the elements to the hashset, the capacity of the hashset grows automatically.
  • HashSet(int capacity, float loadFactor): The capacity of the hashset can be initialized to the capacity of the given integer and to the loadfactor value specified as a parameter in the constructor using this constructor HashSet(int capacity, float loadFactor).
  • HashSet(Collection c): The elements of the collection c are initialized to the hashset using this constructor HashSet(Collection c)

Methods to Implement Java HashSet

The java HashSet class consists of several methods. They are:

  • add(E e): A specific element is added to the set if that particular element is not present in the set using this method Add(E e).
  • clear(): All of the elements from the set are removed using this method Clear().
  • clone(): A shallow copy of the instance of the hashset is returned using this method Clone(). The elements themselves cannot do cloning.
  • contains(Object o): If a specified element is present in the set, this method Contains(object o) returns true.
  • isEmpty(): If there are no elements in the set, this method isEmpty() returns true.
  • iterator(): The iterator over the set elements is returned using this method Iterator().
  • remove(Object o): If a specified element is present in the set, this method Remove(object o) removes that specified element.
  • size(): The count of elements in the set is returned using this method Size().
  • spliterator(): A late binding and a fast spliterator over the elements is the set is created using this method Spliterator().

Examples to Implement HashSet in Java

Below is the example to implement HashSet in Java:

Example #1

Create a hashset and add new elements to the created new set.

Code:

import java.util.HashSet;
import java.util.Set;
//A class Example is created
public class Example {
public static void main(String[] args) {
// A hashset is created
Set<String> months = new HashSet<>();
// New elements are added to the hashset
months.add("January");
months.add("Febraury");
months.add("March");
months.add("April");
months.add("May");
months.add("June");
months.add("July");
months.add("August");
months.add("September");
months.add("October");
months.add("November");
months.add("December");
System.out.println(months);
}
}
Copy after login

Output:

HashSet in Java

Example #2

A collection and demonstrating the use of Hashset(collection c) constructor.

Code:

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
//A class Example is created
public class Example {
public static void main(String[] args)
{
// A hashset is created
List<Integer> Divby4 = new ArrayList<>();
Divby4.add(4);
Divby4.add(8);
Divby4.add(12);
Divby4.add(16);
Divby4.add(20);
List<Integer> Divby2 = new ArrayList<>();
Divby2.add(2);
Divby2.add(4);
Divby2.add(6);
Divby2.add(8);
Divby2.add(10);
// A hashset is created from another collection Divby4
Set<Integer> Divby4Or2 = new HashSet<>(Divby4);
// Adding the elements of divby2 to the existing hashset
Divby4Or2.addAll(Divby2);
System.out.println(Divby4Or2);
}
}
Copy after login

Output:

HashSet in Java

Example #3

Java program to demonstrate operations on hashset like checking if the hashset is empty, checking the count of elements in the hashset and checking if an element exists in the hashset.

Code:

import java.util.HashSet;
import java.util.Set;
//A class Example is created
public class Example {
public static void main(String[] args)
{
// A hashset is created
Set<String> rivers = new HashSet<>();
// performing isempty operation on the set to check if it is empty
System.out.println("Are there no elements in rivers set? : " + rivers.isEmpty());
rivers.add("Kaveri");
rivers.add("Ganga");
rivers.add("Yamuna");
rivers.add("Godavari");
// Checking the size of the hashset
System.out.println("The count of rivers in the hashset are " + rivers.size());
// checking if an element is present in the hashset
String Name = "Ganga";
if(rivers.contains(Name)) {
System.out.println(Name + " is present in the rivers hashset.");
} else {
System.out.println(Name + " is not present in the rivers hashset.");
}
}
}
Copy after login

Output:

HashSet in Java

Example #4

Java program to remove one element from a hashset, remove all the elements that belong to a different collection, remove those elements that satisfy a certain condition from the hashset and remove all the elements from the hashset.

Code:

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
//A class Example is created
public class Example {
public static void main(String[] args)
{
// A hashset is created
Set<Integer> num = new HashSet<>();
num.add(2);
num.add(3);
num.add(4);
num.add(5);
num.add(6);
num.add(7);
num.add(8);
num.add(9);
num.add(10);
System.out.println("Numbers added to the hashset are : " + num);
// An element from the hashset is removed. False is returned if that element doesnt     exists in the hashset
boolean Remove = num.remove(5);
System.out.println("After remove the number 5 from the hashset, the remaining elemnts are => " + num);
// all the elements that belong to a different collection are removed from the hashset
List<Integer> Squares = new ArrayList<>();
Squares.add(4);
Squares.add(9);
num.removeAll(Squares);
System.out.println("After removing all the elements that belong to a different collection => " + num);
// Elements matching a certain condition is removed from the hashset
num.removeIf(num1 -> num1 % 2 == 0);
System.out.println("After removing all the elements matching a certain condition is removed from the hashset => " + num);
// Clearing the hashset
num.clear();
System.out.println("After clearing the hashset => " + num);
}
}
Copy after login

Output:

HashSet in Java

Conclusion

In this tutorial, we understand the concept of Hashset as in the definition of hashset, the syntax to create an hashset, constructors in hashset, methods in hashset, and programming examples for the creation of hashset, adding elements to a newly created hashset, removing the elements from an existing hashset, checking for an element in the hashset.

The above is the detailed content of HashSet in Java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template