HashSet add() Method in Java

Published by user on

The add(E element) method of HashSet inserts the specified element into the set. It returns false if the set already contains the specified element otherwise returns true.

Syntax

boolean add(E element)

Parameters

e is the element to insert into set

Program 1

import java.util.HashSet;

public class HashSetAddExample {

	public static void main(String[] args) {

		HashSet<Integer> set = new HashSet<>();
		set.add(10);
		set.add(20);
		set.add(30);
		set.add(40);
		set.add(50);

		System.out.println("Set elements: " + set);
	}
}

Output

Set elements: [50, 20, 40, 10, 30]

Program 2

import java.util.HashSet;

public class HashSetAddExample {

	public static void main(String[] args) {

		HashSet<String> set = new HashSet<>();
		set.add("India");
		set.add("Pakistan");
		set.add("Srilanka");
		set.add("Australia");
		set.add("England");

		System.out.println("Set elements: " + set);
	}
}

Output

Set elements: [Srilanka, Pakistan, England, Australia, India]

Program 3

import java.util.HashSet;

class Employee {
	private int employeeId;
	private String employeeName;

	public Employee() {
	}

	public Employee(int employeeId, String employeeName) {
		super();
		this.employeeId = employeeId;
		this.employeeName = employeeName;
	}

	@Override
	public String toString() {
		return "Employee [employeeId=" + employeeId + ", employeeName=" + employeeName + "]";
	}
}

public class HashSetAddExample {

	public static void main(String[] args) {

		HashSet<Employee> employees = new HashSet<>();
		employees.add(new Employee(101, "Adam"));
		employees.add(new Employee(102, "Rikcy"));
		employees.add(new Employee(103, "Shaun"));
		employees.add(new Employee(104, "Chris"));
		System.out.println("Set elements");
		for (Employee employee : employees) {
			System.out.println(employee);
		}
	}
}

Output

Set elements
Employee [employeeId=101, employeeName=Adam]
Employee [employeeId=102, employeeName=Rikcy]
Employee [employeeId=103, employeeName=Shaun]
Employee [employeeId=104, employeeName=Chris]
Categories: Java

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *