提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
使用==和!=运算符。
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