How to Add Unique Objects in HashSet in Java

In this tutorial we will see how to add unique objects in hashset in java . We knew that hashset does not contain duplicates in java. Because We have read about that Set uses internally map to store data.If we use user defined object as key in map or value in set then it is must  override hashcode() and equal() method .

How to Add Unique Objects in HashSet in Java?

In this example we will create one User class and add object of User class . We will also create HAshSet of User class type. Now we add objects of User class to HashSet using add() method. As we knew that HashSet does not allow duplicates . We will create two object user1 , user2 with same data and add to HashSet .

import java.util.HashSet;

public class HashSetOfObject {
	public static void main(String[] args) {

		HashSet<User> hashSet = new HashSet<User>();
		User user1 = new User("amit", 10);
		User user2 = new User("amit", 10);
		hashSet.add(user1);
		hashSet.add(user2);
		//print hashset
		System.out.println("hashset is = "+ hashSet);
	}
}

class User {

	private String name;
	private int userId;

	public User(String name, int userId) {
		super();
		this.name = name;
		this.userId = userId;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getUserId() {
		return userId;
	}

	public void setUserId(int userId) {
		this.userId = userId;
	}

	@Override
	public String toString() {
		return "[name=" + name + ", userId=" + userId + "]";
	}
	
	

}

Output :

hashset is = [[name=amit, userId=10], [name=amit, userId=10]]

As per output user1 and user2 are different object even their values are same. Set does not contain duplicates in java , Its means User objects user1 and user2 are not same . The solution of this problem is we must  override hashcode() and equal() method into User class .

import java.util.HashSet;

public class HashSetOfObject {
	public static void main(String[] args) {

		HashSet<User> hashSet = new HashSet<User>();
		User user1 = new User("amit", 10);
		User user2 = new User("amit", 10);
		hashSet.add(user1);
		hashSet.add(user2);
		//print hashset
		System.out.println("hashset is = "+ hashSet);
	}
}

class User {

	private String name;
	private int userId;

	public User(String name, int userId) {
		super();
		this.name = name;
		this.userId = userId;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getUserId() {
		return userId;
	}

	public void setUserId(int userId) {
		this.userId = userId;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		result = prime * result + userId;
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		User other = (User) obj;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		if (userId != other.userId)
			return false;
		return true;
	}

	@Override
	public String toString() {
		return "[name=" + name + ", userId=" + userId + "]";
	}

}

Output :

hashset is = [[name=amit, userId=10]]

In this tutorial we have learned how to add unique objects in HashSet in java with nice example .  You can try more HashSet example in java

Reference :

Java Doc – HashSet

Leave a Reply

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

− 1 = 1