hashcode与字符串

http://blog.csdn.net/zwy9002/article/details/7592719

问题1. 不同的字符串可能会有相同的HashCode吗?

答案: 可能。hashcode是用来判断两个字符串是否相等的依据,不同的字符串不可能有相同的hashcode,但不同的hashCode经过与长度的取余,就很可能产生相同的hashCode,就是所谓的哈希冲突. 如:

 

	public static void main(String[] args) {

		int hash1 = "ABCDEa123abc".hashCode();
		int hash2 = "ABCDFB123abc".hashCode();
		System.out.println(hash1);
		System.out.println(hash2);
	}

output:
165374702
165374702 

 

延伸问题: hashcode相同,字符串相同吗?答案是不一定。

问题2. 相同的字符串可能会有不同的HashCode吗

答案: 不可能。

如果你自己重写equals和hashcode方法是可以实现的,但是java规范要求两个equals的对象一定要有相同的hashcode。
String类是jdk里的基础类,是严格遵守规范的,而且是final的,不能继承,所以也没有重写覆盖hashcode方法的可能。
问题3. 相同的字符串每次生成的HashCode都相同吗?
答案: 一定相同。
hashcode是由简单的Hash算法得出来的,根据字符串的值算出来的,每次算出来的结果都相同 
posted @ 2013-10-29 10:17  悟寰轩-叶秋  阅读(1915)  评论(0编辑  收藏  举报