欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

为什么重写equals()和hashcode()

发布时间:2025/3/19 编程问答 55 豆豆
生活随笔 收集整理的这篇文章主要介绍了 为什么重写equals()和hashcode() 小编觉得挺不错的,现在分享给大家,帮大家做个参考.
首先写个例子 public class TestTest{String name ;TestTest(String name){this.name = name;} public static void main(String[] args){TestTest test1 = new TestTest("hello");TestTest test2 = new TestTest("hello");System.out.println("输出test1是否等于test2:"+test1.equals(test2));//如果不重写equals()两者不等,重写相等Map<TestTest, String> map = new HashMap<>(4);map.put(test1, "hello");String hello = map.get(test2);System.out.println(hello);//结果为null,添加重写后会拿到hello }

//添重写后

@Override public boolean equals(Object o) {if (this == o) return true;if (o == null || getClass() != o.getClass()) return false;TestTest testTest = (TestTest) o;return name.equals(testTest.name); }@Override public int hashCode() {return Objects.hash(name); } }

因为默认情况下会调用Object的equals(),hashcode(),而map中get时get获取的hashCode是hashMap中的hash()来获取地址所以不一致,这也是为什么通常用String或Integer等final 并且重写了hashCode和equals类来做键值来防止键值被重写。下图是object的两个被重写的方法:

 

总结

以上是生活随笔为你收集整理的为什么重写equals()和hashcode()的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。