您的位置:首页 > 编程语言 > Java开发

【java基础学习-2--】关于Hashcode()的使用

2015-08-23 10:05 731 查看

摘要

Java中equals()和hashCode()有一个契约:
如果两个对象相等的话,它们的hash code必须相等;

但如果两个对象的hash code相等的话,这两个对象不一定相等;

这个约定直接导致了如下3个规则:
:无论你何时实现 equals 方法,你必须同时实现 hashCode 方法;

永远不要把哈希码误用作一个key;

在分布式应用中不要使用哈希码;

需要说明的是:关于规则2:《永远不要把哈希码误用作一个key》
==>也可以将哈希码作为key,但需要经过2步去处理:
对键采用hashCode()计算出来的值;==>这样可以找出哈希码相同,但是不相等对象的集合;

对这个集合使用键的equals()方法来进行线性查找,直到找到要找的对象;

测试程序1:(同时实现了equals()方法和Hashcode()方法)

package com.ll.hashcode;import java.util.HashMap;public class HashcodeTest { private String color; public HashcodeTest(String color) { this.color = color; } @SuppressWarnings("unchecked") public static void main(String[] args) { HashcodeTest a1 = new HashcodeTest("green"); HashcodeTest a2 = new HashcodeTest("red"); //hashMap stores apple type and its quantity HashMap m = new HashMap(); m.put(a1, 10); m.put(a2, 20); System.out.println(m.get(new HashcodeTest("green"))); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((color == null) ? 0 : color.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; HashcodeTest other = (HashcodeTest) obj; if (color == null) { if (other.color != null) return false; } else if (!color.equals(other.color)) return false; return true; }}结果:


测试程序2(只实现了equals()方法,未实现Hashcode()方法)

package com.ll.hashcode;import java.util.HashMap;public class HashcodeTest { private String color; public HashcodeTest(String color) { this.color = color; } public boolean equals(Object obj) { if (!(obj instanceof HashcodeTest)) return false; if (obj == this) return true; return this.color.equals(((HashcodeTest) obj).color); } @SuppressWarnings("unchecked") public static void main(String[] args) { HashcodeTest a1 = new HashcodeTest("green"); HashcodeTest a2 = new HashcodeTest("red"); //hashMap stores apple type and its quantity HashMap m = new HashMap(); m.put(a1, 10); m.put(a2, 20); System.out.println(m.get(new HashcodeTest("green"))); }}结果:

参考链接:

《Java中的equals()和hashCode()契约》:http://www.importnew.com/8701.html 《关于 hashCode() 你需要了解的 3 件事》:http://www.importnew.com/16517.html

来自为知笔记(Wiz)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: