我正在尝试覆盖Java中的equals方法。我有一节课People
它基本上有2个数据字段name
和age
。现在我想覆盖equals
方法,这样我就可以在两个People对象之间进行检查。
我的代码如下
public boolean equals(People other){
boolean result;
if((other == null) || (getClass() != other.getClass())){
result = false;
} // end if
else{
People otherPeople = (People)other;
result = name.equals(other.name) && age.equals(other.age);
} // end else
return result;
} // end equals
但当我写下age.equals(other.age)
它给了我错误,因为equals方法只能比较字符串和年龄是整数。
解决方案
我用过==
运算符,我的问题就解决了。
发布于 2011-11-18 18:25:46
//Written by K@stackoverflow
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
ArrayList people = new ArrayList();
people.add(new Person("Subash Adhikari", 28));
people.add(new Person("K", 28));
people.add(new Person("StackOverflow", 4));
people.add(new Person("Subash Adhikari", 28));
for (int i = 0; i < people.size() - 1; i++) {
for (int y = i + 1; y <= people.size() - 1; y++) {
boolean check = people.get(i).equals(people.get(y));
System.out.println("-- " + people.get(i).getName() + " - VS - " + people.get(y).getName());
System.out.println(check);
}
}
}
}
//written by K@stackoverflow
public class Person {
private String name;
private int age;
public Person(String name, int age){
this.name = name;
this.age = age;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (obj.getClass() != this.getClass()) {
return false;
}
final Person other = (Person) obj;
if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) {
return false;
}
if (this.age != other.age) {
return false;
}
return true;
}
@Override
public int hashCode() {
int hash = 3;
hash = 53 * hash + (this.name != null ? this.name.hashCode() : 0);
hash = 53 * hash + this.age;
return hash;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
输出:
运行:
-- Subash Adhikari - VS -K false
-- Subash Adhikari - VS - StackOverflow false
-- Subash Adhikari - VS - Subash Adhikari true
-- K- VS - StackOverflow false
-- K- VS - Subash Adhikari false
-- StackOverflow - VS - Subash Adhikari false
--构建成功(总时间:0秒)
发布于 2011-11-18 17:49:28
引入更改参数类型的新方法签名称为重载
public boolean equals(People other){
这里People
不同于Object
。
当方法签名与其超类的签名保持相同时,将调用该方法签名覆盖和@Override
注释有助于在编译时区分这两者:
@Override
public boolean equals(Object other){
在没有看到实际声明的情况下age
,很难说为什么会出现这个错误。
发布于 2011-11-18 17:45:25
我不确定细节,因为你还没有发布完整的代码,但是:
记住覆盖还有hashCode()
the equals
方法应具有Object
,notPeople
作为其参数类型。目前您正在重载equals方法,而不是重写equals方法,这可能不是您想要的,特别是考虑到您稍后会检查它的类型。
您可以使用instanceof
要检查它是一个人物对象,例如if (!(other instanceof People)) { result = false;}
equals
用于所有对象,但不是基元。我想你的意思是年龄是一个int
(原语),在这种情况下只需使用==
。请注意,Integer (带有大写'I')是一个对象,应该与equals进行比较。
请参见What issues should be considered when overriding equals and hashCode in Java?了解更多详细信息。
https://stackoverflow.com/questions/8180430
复制相似问题