Store User type Object to HashSet in java

HashSet dnt store duplicates. here employee object storing in hashset mean based on id duplicate object can't be store in HashSet. so override equals and hashCode methods for id.


import java.util.HashSet;
import java.util.Set;

class Emp{

int id;
String name;

Emp(int id, String name){
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
@Override
public String toString() {
return "Emp [id=" + id + ", name=" + name + "]";
}

@Override

public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Emp other = (Emp) obj;
if (id != other.id)
return false;
return true;
}
 }

  public class EmployeHashSet {

public static void main(String[] args) {
Set<Emp> set = new HashSet<>();
Emp e1 = new Emp(1,"AAA");
Emp e2 = new Emp(1,"VVV");
Emp e3 = new Emp(2,"V3VV");

set.add(e1);
set.add(e2);
set.add(e3);

System.out.println(set);

}
}

Output : [Emp [id=1, name=AAA], Emp [id=2, name=V3VV]]






Post a Comment

Previous Post Next Post