我试图在Java中重写等于方法。我有课People其中基本上有两个数据字段。name和age..现在我想重写equals方法,这样我就可以在两个人对象之间进行检查。我的代码如下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)它给了我错误,因为等于方法只能比较字符串和年龄是整数。解我用==如建议的运算符,我的问题就解决了。如何在Java中覆盖等于方法
3 回答
DIEA
TA贡献1820条经验 获得超3个赞
//Written by K@stackoverflowpublic class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
ArrayList<Person> people = new ArrayList<Person>();
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@stackoverflowpublic 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 (!Person.class.isAssignableFrom(obj.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秒)
神不在的星期二
TA贡献1963条经验 获得超6个赞
记得重写 hashCode()也是 这个 equals方法应该有 Object,不是 People作为它的参数类型。目前,您正在重载,而不是重写相等方法,这可能不是您想要的,特别是考虑到稍后检查它的类型。 你可以用 instanceof检查它是一个人的对象。 if (!(other instanceof People)) { result = false;}equals用于所有对象,但不用于原语。我觉得你的平均年龄是 int(原语),在这种情况下,只需使用 ==..请注意,Integer(带有大写“i”)是一个对象,应该将其与等于进行比较。
添加回答
举报
0/150
提交
取消
