java 什么重写了equals_Java中如何重写equals方法

一、概述

我想覆盖Java中的equals方法。我有一个类People,基本上有2个数据字段name和age。现在,我想重写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方法只能比较String并且age是Integer。

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

二、详解

引入一种可以更改参数类型的新方法签名称为重载:

public boolean equals(People other){

这People与有所不同Object。

当一个方法签名与其父类的签名相同时,它被称为覆盖(overriding),@Override注释在编译时有助于区分两者:

@Override

public boolean equals(Object other){

没有看到的实际声明age,很难说出错误出现的原因。

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

-Subash Adhikari-VS-StackOverflow否

-Subash Adhikari-VS-Subash Adhikari是

-K-VS-StackOverflow错误

-K-VS-Subash Adhikari错误

-StackOverflow-VS-Subash Adhikari错误

-建立成功(总时间:0秒)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值