首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 企业软件 > 行业软件 >

String种的hashcode算法

2013-07-27 
String类的hashcode算法源:http://josephmok.iteye.com/blog/631181评:搞了一晚上的equals()方法和hashCod

String类的hashcode算法

源:http://josephmok.iteye.com/blog/631181

评:

搞了一晚上的equals()方法和hashCode() 与 == 之间的关系
还是可以嘛
未重写equals()比较对象是返回true,则说明两个对象相等(即引用同一个对象) 其hashcode值应该相等。
不同对象,用equals方法肯定是返回false,但是其hashcode可能相等也可能不相等。
== 只能比较基本类型
重写过的equals方法比较内容是否相等。如字符串的比较 是重写了equals方法
String X=“abc”;
String Y=“abc”;
由下面的算法可以得到相同的hashcode
所以 X.equals(Y) 返回true


public class CreateHashCode
{
public static void main(String[] args){

String ss = new String ("abc");
CreateHashCode c1 = new CreateHashCode();
System.out.println(c1.hashcode(ss));? //自己方法
System.out.println(ss.hashCode());? //类库方法 返回结果应该相同 验证后的确相等
}
public int? hashcode(String str){

char[] chars;

chars = str.toCharArray();

int n = chars.length;

int result=0;

for (int i = 0;i<n ;i++ )
{

result+=java.lang.Math.pow(31,n-1-i)*chars[i];?
?????????????????????????????????????? //String的hashcode算法

?? //API中String的hashCode()方法返回:s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
//api中 for (int i = 0; i < len; i++) {
??????????????? h = 31*h + val[off++];
??????????? }? 这么写的,这边简化了,1.6如此

}
return result;
}
}

热点排行