java 重写equal_equal 如何重写hashcode

如何重写hashCode()和equals()方法

直接上刺刀了

定义一个学生类

class Student{

private String name;

private int age;

// getters and setters

}

重写equal方法

重写equal 使当学生的姓名和年龄相同时候就判断他们为同一个学生

1. 判断是否等于自身.

2使用instanceof运算符判断 other 是否为Student类型的对象.

3. 比较Student类中你自定义的数据域,name和age,一个都不能少.

具体代码如下

@Override

public boolean equals(Object other) {

System.out.println(“equals method invoked!”);

if(other == this)

return true;

if(!(other instanceof Student))

return false;

Studento = (Student)other;

return o.name.equals(name) && o.age == age;

}

重写equals()而不重写hashCode()的风险

构造一个hashset和两个对象

Set set = new HashSet();

set.add(c1);

Studentc1 = new Student(“yq1012”, 10);

Studentc2 = new Coder(“yq1012”, 10);

System.out.println(set.contains(c2)); //结果为false

因此,我们重写hashCode()的目的在于,在A.equals(B)返回true的情况下,A, B 的hashCode()要返回相同的值.

如何重写hashcode

@Override

public int hashCode() {

int result = 14;

result = result * 31 + name.hashCode();

result = result * 31 + age;

return result;

}

注:这里最好重写的时候不要返回固定值,如果hashCode()每次都返回相同的数,那么所有的对象都会被放到同一个bucket中,每次执行查找操作都会遍历链表,这样就完全失去了哈希的作用

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值