Determine whether the two object references point to the same object - Java Object Oriented Design

Java examples for Object Oriented Design:equals method

Introduction

Use the == and != operators.

Demo Code

public class Main {
  public static void main(String[] args) {

    // Compare if two objects contain the same values
    Team team1 = new Team();
    Team team2 = new Team();

    team2.setName("Nicks");
    team2.setCity("Main");
    if (team1 == team2) {
      System.out.println("These object references refer to the same object.");
    } else {//from w w w . j ava 2 s  . c  om
      System.out
          .println("These object references do NOT refer to the same object.");
    }

    // Compare two objects to see if they refer to the same object
    Team team3 = team1;
    Team team4 = team1;

    if (team3 == team4) {
      System.out.println("These object references refer to the same object.");
    } else {
      System.out
          .println("These object references do NOT refer to the same object.");
    }
  }
}

class Team {
  private String name;
  private String city;
  private volatile int cachedHashCode = 0;

  /**
   * @return the name
   */
  public String getName() {
    return name;
  }

  /**
   * @param name
   *          the name to set
   */
  public void setName(String name) {
    this.name = name;
  }

  /**
   * @return the city
   */
  public String getCity() {
    return city;
  }

  /**
   * @param city
   *          the city to set
   */
  public void setCity(String city) {
    this.city = city;
  }

  public String getFullName() {
    return this.name + " - " + this.city;
  }

  @Override
  public boolean equals(Object obj) {

    if (this == obj) {
      return true;
    }
    if (obj instanceof Team) {
      Team other = (Team) obj;
      return other.getName().equals(this.getName())
          && other.getCity().equals(this.getCity());
    } else {
      return false;
    }

  }

  @Override
  public int hashCode() {
    int hashCode = cachedHashCode;
    if (hashCode == 0) {
      String concatStrings = name + city;
      hashCode = concatStrings.hashCode();
    }
    return hashCode;
  }
}

Result


Related Tutorials