集册 Java实例教程 确定两个对象是否包含相同的值

确定两个对象是否包含相同的值

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

668
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
使用equals()方法。
// 来自 nowjava

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("Bates");

    team2.setCity("York");

    if (team1.equals(team2)){

      System.out.println("These object references contain the same values.");

  } else {

      System.out.println("These object references do NOT contain the same values.");

  }


    // Compare two objects to see if they refer to the same object

    Team team3 = team1;

    Team team4 = team1;


    if (team3.equals(team4) ) {

      System.out.println("These object references refer to the same object.");

    } else {// from nowjava - 时代Java

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