k4h4shi
9/3/2017 - 11:16 AM

equals And hashcode of Java

equals And hashcode of Java

import java.util.Objects;
import org.apache.commons.lang.builder.ToStringBuilder;

public class Point {
  private final int x;
  private final int y;
  
  public Point(int x, int y) {
    this.x = x;
    this.y = y;
  }
  
  public int getX() {
    return x;
  }
  
  public int getY() {
    return y;
  }
  
  
  
  @Override
  public int hashCode() {
    return Objects.hash(this.x, this.y);
  }

  @Override
  public boolean equals(Object obj) {
    if (this == obj)
      return true;
    if (obj == null)
      return false;
    if (getClass() != obj.getClass())
      return false;
    Point other = (Point) obj;
    if (x != other.x)
      return false;
    if (y != other.y)
      return false;
    return true;
  }
  
  @Override
  public String toString() {
    return ToStringBuilder.reflectionToString(this);
  }

  public static void main(String[] args) {
    Point point1 = new Point(3, 2);
    Point point2 = new Point(3, 2);
    
    System.out.println(point1);
    System.out.println(point2);
    
    System.out.println(point1.hashCode());
    System.out.println(point2.hashCode());
    
    System.out.println(point1.equals(point2));
  }
}
import java.util.HashSet;
import java.util.Set;

public class Employee {
  private int employeeNo;
  private String employeeName;
  
  public Employee(int employeeNo, String employeeName) {
    this.employeeNo = employeeNo;
    this.employeeName = employeeName;
  }
  
  public boolean equals(Object obj) {
    if (this == obj) {
      return true;
    }
    if (obj == null) {
      return false;
    }
    if (getClass() != obj.getClass()) {
      return false;
    }
    Employee other = (Employee) obj;
    if(this.employeeNo != other.employeeNo) {
      return false;
    }
    if(employeeName == null) {
      if(other.employeeName != null) {
        return false;
      }
    } else if (!employeeName.equals(other.employeeName)) {
      return false;
    }
    return true;
  }
  
  public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + employeeNo;
    result = prime * result + ((employeeName == null) ? 0 : employeeName.hashCode());
    return result;
  }
  
  public static void main(String[] args) {
    Employee employee1 = new Employee(1, "山田 太郎");
    Employee employee2 = new Employee(1, "山田 太郎");
    Set<Employee> employees = new HashSet<>();
    employees.add(employee1);
    employees.add(employee2);
    System.out.println(employees.size()); 
  }
}