gpt4 book ai didi

java - Java中如何重写equals方法

转载 作者:IT老高 更新时间:2023-10-28 11:30:03 24 4
gpt4 key购买 nike

我正在尝试覆盖 Java 中的 equals 方法。我有一个类 People,它基本上有 2 个数据字段 nameage。现在我想重写 equals 方法,以便我可以检查 2 个 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 方法只能比较字符串并且年龄是整数。

解决方案

我按照建议使用了 == 运算符,我的问题解决了。

最佳答案

//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<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@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;
}
}

输出:

run:

-- 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

-- BUILD SUCCESSFUL (total time: 0 seconds)

关于java - Java中如何重写equals方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8180430/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com