集册 Java实例教程 确定两个对象引用是否指向同一对象

确定两个对象引用是否指向同一对象

欢马劈雪     最近更新时间:2020-01-02 10:19:05

708
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
使用==和!=运算符。

public class Main {

  public static void main(String[] args) {//nowjava.com - 时  代  Java 提 供


    // 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 {

      System.out

          .println("These object references do NOT refer to the same object.");/*nowjava.com 提供*/

    }


    // 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.ge
展开阅读全文