Internal concept of Hashset in java
package govind;
public class Employee
{
private String name;
public Employee(String name) {
super();
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Employee Name="+name;
}
@Override
public int hashCode() {
System.out.println("Hashcode="+name);
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
System.out.println("equals="+name);
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Employee other = (Employee) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
==========================================================================================================================================
package govind;
import java.util.HashSet;
public class HashsetEmployeeMain
{
public static void main(String[] args)
{
HashSet<Employee> employee=new HashSet<>();
employee.add(new Employee("god"));
employee.add(new Employee("god"));
System.out.println(employee);
}
}
===========================================================================================================================================
o/p:--------------------------------------
Hashcode=god
Hashcode=god
equals=god
[Employee Name=god]
package govind;
public class Employee
{
private String name;
public Employee(String name) {
super();
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Employee Name="+name;
}
@Override
public int hashCode() {
System.out.println("Hashcode="+name);
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
System.out.println("equals="+name);
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Employee other = (Employee) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
==========================================================================================================================================
package govind;
import java.util.HashSet;
public class HashsetEmployeeMain
{
public static void main(String[] args)
{
HashSet<Employee> employee=new HashSet<>();
employee.add(new Employee("god"));
employee.add(new Employee("god"));
System.out.println(employee);
}
}
===========================================================================================================================================
o/p:--------------------------------------
Hashcode=god
Hashcode=god
equals=god
[Employee Name=god]