Java class definition create Person class with hashCode() and equals()

Description

Java class definition create Person class with hashCode() and equals()

public class Main {
  public static void main(String[] args) {
    Person p = new Person("CSS","HTML");
    Person p2 = new Person("CSS","HTML");
    //from www .  j  a v a2  s . c om
    System.out.println(p == p2);
    System.out.println(p.equals(p2));
    
    System.out.println(p.hashCode());
    System.out.println(p2.hashCode());
  }
}

class Person {
  private String lastName;
  private String firstName;

  public Person(String lastName, String firstName) {
    super();
    this.lastName = lastName;
    this.firstName = firstName;
  }

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

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

  public String getLastName() {
    return lastName;
  }

  public String getFirstName() {
    return firstName;
  }
}



PreviousNext

Related