String的public int hashCode() Returns a hash code for this string. The hash code for a String object is computed as s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
using int arithmetic, where s[i] is the ith character of the string, n is the length of the string, and ^ indicates exponentiation. (The hash value of the empty string is zero.)
通过这个方法可以获得调用者的散列码;在通常的使用中是用不到这个方法的;如果想要获得Map中某个值可以采用下面的方法:
import java.util.*;class hashmaptest
{
public static void main(String args[])
{
HashMap hm = new HashMap();
hm.put("AA", new Integer(11));
hm.put("BB", new Integer(222));
Set set = hm.entrySet();
Iterator i = set.iterator();
while(i.hasNext())
{
Map.Entry me = (Map.Entry)i.next();
System.out.println(me.getKey() + ":" + me.getValue());
}
}
}
import java.util.*;public class Name implements Comparable {
private String firstName, lastName; public Name(String firstName, String lastName) {
if (firstName==null || lastName==null)
throw new NullPointerException();
this.firstName = firstName;
this.lastName = lastName;
} public String firstName() {return firstName;}
public String lastName() {return lastName;} public boolean equals(Object o) {
if (!(o instanceof Name))
return false;
Name n = (Name)o;
return n.firstName.equals(firstName) &&
n.lastName.equals(lastName);
}
// 重新定义了hashCode方法,本质上讲相同的对象应该有相同的散列码
public int hashCode() {
return 31*firstName.hashCode() + lastName.hashCode();
} public String toString() {return firstName + " " + lastName;} public int compareTo(Object o) {
Name n = (Name)o;
int lastCmp = lastName.compareTo(n.lastName);
return (lastCmp!=0 ? lastCmp :
firstName.compareTo(n.firstName));
}
}
这个hashCode主要是针对这个方法
因为:
Equal objects must have equal hash codes
hashCode()的值,为什么全是0呢?!!
Returns a hash code for this string. The hash code for a String object is computed as
s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
using int arithmetic, where s[i] is the ith character of the string, n is the length of the string, and ^ indicates exponentiation. (The hash value of the empty string is zero.)