我来自C ++背景,今天刚刚开始使用Java。假设我有一个包含几个数据成员的类。例如:
public class Person {
//Constructors/Destructor
public Person(String strFirstName, String strLastName) {
m_strFirstName = strFirstName;
m_strLastName = strLastName;
m_strFullName = m_strFirstName + m_strLastName;
}
//Getters
public String GetFullName() { return m_strFullName; }
public String GetFirstName() { return m_strFirstName; }
public String GetLastName() { return m_strLastName; }
//Private Data Members
private String m_strFirstName;
private String m_strLastName;
private String m_strFullName;
}
现在让我说我这样做:
Person john = new Person("john", "doe");
Person johndoe = new Person("john", "doe");
if (john == johndoe) {
System.out.println("They are Equal");
} else {
System.out.println("They are NOT Equal");
}
结果是“他们不等于”。我理解这是因为Java正在比较引用(内存地址),并且因为它们是内存中的不同位置,所以测试失败。我已经读过Java不支持运算符重载,所以我不能重载运算符==,那么有一个方法我会覆盖它来实现我的成员比较吗? object.equals方法看起来很有前景,但我已经读过,不好的做法是覆盖这个。
更新: 好的,我确信压倒平等是可以的!我找不到那篇说它不好的文章。感谢您的帮助,我学习Java时可能会有更多问题!
答案 0 :(得分:6)
你这样做:
if (john.equals(johndoe)) {
...
}
并在您的对象上实现equals()
方法:
public class Person {
private String firstName;
private String lastName;
private String fullName;
public Person(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
this.fullName = firstName + lastName;
}
public String getFirstName() { return firstName; }
public String getLastName() { return lastName; }
public String getFullName() { return fullName; }
@Override
public boolean equals(Object ob) {
if (ob == null) return false;
if (ob.getClass() != getClass()) return false;
Person other = (Person)ob;
if (!firstName.equals(other.firstName)) return false;
if (!lastName.equals(other.lastName)) return false;
if (!(fullName.equals(other.fullName)) return false;
return true;
}
@Override
public int hashCode() {
return firstName.hashCode() ^ lastName.hashCode() ^ fullName.hashCode();
}
}
有两点需要注意:
答案 1 :(得分:2)
你在哪里读到这是不好的做法?在Java中重载equals
(和hashCode
)是很常见的。请参阅What issues should be considered when overriding equals and hashCode in Java?。