API上说返回一个MAP的值,是说每一个MAP都有一个特定的hashCode()吗?

解决方案 »

  1.   

    不只是Map,Java中大部分的类都已经有了hashCode()方法,比如String等。
    通过这个方法可以获得调用者的散列码;在通常的使用中是用不到这个方法的;如果想要获得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());
    }

    }
    }
      

  2.   

    可以说每一个,都有一个特定的hashCode()吗?
      

  3.   

    比较:
    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));
        }
    }
      

  4.   

    Object 对象中有方法 equals(Object obj)
    这个hashCode主要是针对这个方法
    因为:
    Equal objects must have equal hash codes
      

  5.   

    是每一个对象,都有一个它自己的hashCode()值吗?
      

  6.   

    小弟请教,hashCode()不是每一个对象,都有不同的值吗?小弟建了4个,String的对象,并打印了
    hashCode()的值,为什么全是0呢?!!
      

  7.   

    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.)