Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package collection;
- import java.util.ArrayList;
- import java.util.HashSet;
- import java.util.List;
- import java.util.Set;
- public class HashCodeEqualsDemo {
- public static void main(String[] args) {
- // Add method of set will first check for hashcode, if method is not found, it
- // will create a new Object even if equals has been overridden
- // If hashcode has been overridden, and two employees have same id (thus same hashcode
- // as per our implementation), it will execute equals method, to find if two objects are equal.
- // For set to work properly for a custom reference type, it is mandatory to override both hashcode and equals
- Set<Employee> employeeSet = new HashSet<>();
- employeeSet.add(new Employee("ABC", "abc@gmail.com", 123));
- employeeSet.add(new Employee("ABC", "abc@gmail.com", 123));
- employeeSet.add(new Employee("XYZ", "abc@gmail.com", 100));
- employeeSet.add(new Employee("XYZ", "xyz@gmail.com", 123));
- System.out.println(employeeSet.size()); // 3
- //Add method of list will just check the equality using equals method. Following will work even if
- // hashcode has not been overridden.
- List<Employee> employeeList = new ArrayList<>();
- employeeList.add(new Employee("ABC", "abc@gmail.com", 123));
- employeeList.add(new Employee("ABC", "abc@gmail.com", 123));
- employeeList.add(new Employee("XYZ", "abc@gmail.com", 100));
- employeeList.add(new Employee("XYZ", "xyz@gmail.com", 123));
- System.out.println(employeeList.contains(new Employee("ABC", "abc@gmail.com", 123))); // true
- System.out.println(employeeList.contains(new Employee("PQR", "pqr@gmail.com", 500))); // false
- System.out.println(employeeList.contains(new Employee("PQR", "abc@gmail.com", 500))); // true
- }
- }
- class Employee {
- private String name;
- public int getId() {
- return id;
- }
- public void setId(int id) {
- this.id = id;
- }
- private int id;
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public String getEmail() {
- return email;
- }
- public void setEmail(String email) {
- this.email = email;
- }
- private String email;
- Employee(String name, String email, int id) {
- this.name = name;
- this.email = email;
- this.id = id;
- }
- @Override
- public boolean equals(Object object) {
- System.out.println("Equals called");
- if (this == object) {
- return true;
- }
- if (object == null || (this.getClass() != object.getClass()))
- return false;
- Employee employee = (Employee) object;
- return this.email.equals(employee.email);
- }
- @Override
- public int hashCode() {
- System.out.println("hashcode called");
- return this.id;
- }
- }
Add Comment
Please, Sign In to add comment