首页 javaWEB equal 如何重写hashcode

equal 如何重写hashcode

如何重写hashCode()和equals()方法 直接上刺刀了 定义一个学生类 class Student{ priv…

如何重写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<Student> set = new HashSet<Student>();

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中,每次执行查找操作都会遍历链表,这样就完全失去了哈希的作用

 

免责声明:文章内容不代表本站立场,本站不对其内容的真实性、完整性、准确性给予任何担保、暗示和承诺,仅供读者参考,文章版权归原作者所有。如本文内容影响到您的合法权益(内容、图片等),请及时联系本站,我们会及时删除处理。

为您推荐

nodejs 整理记录

nodejs 整理记录

下载包 https://blog.csdn.net/m0_59878114/article/details/120274...
websocket测试html

websocket测试html

<!DOCTYPE html> <html> <head> <meta cha...
bigdemical两个数比较大小

bigdemical两个数比较大小

/*int result = bigdemical1.compareTo(bigdemical2) result = -...
Beetl2.7 中文文档

Beetl2.7 中文文档

Beetl目前版本是2.7.23,相对于其他java模板引擎,具有功能齐全,语法直观,性能超高,以及编写的模板容易维护等...
纯CSS实现多个便签在一行展示,拖动滚动

纯CSS实现多个便签在一行展示,拖动滚动

div <h2>请注意需要在移动端预览,PC端拖拽无效果</h2> <div class=...
返回顶部