日期:2014-05-20 浏览次数:20948 次
package wukun;   
  
public class Stu {   
    private String name;   
    private String sex;   
       
    public Stu(String name, String sex) {   
        super();   
        this.name = name;   
        this.sex = sex;   
    }   
}  
package wukun;   
  
import java.util.ArrayList;   
import java.util.HashSet;   
import java.util.Set;   
  
public class HashCodeTest {   
       
    public static void main(String[] args) {   
           
//      Set h1 = new HashSet();   
//      Set h2 = new HashSet();   
//         
//      ArrayList a1 = new ArrayList();   
//      ArrayList a2 = new ArrayList();   
//         
////        a1.add(new String("abc"));     
////        a2.add(new String("abc"));   
//         
//      h1.add(a1);   
//      h2.add(a2);   
//         
//      System.out.println(h1.hashCode());   
//      System.out.println(h2.hashCode());   
//         
        Stu s1 = new Stu("wukun","男");   
        Stu s2 = new Stu("wukun","男");   
           
        System.out.println(s1.hashCode());   
        System.out.println(s2.hashCode());   
           
    }   
} 
为什么2个ArrayList的hash码一样,而2个自定义的stu对象的hash码就不一样呢?(主要问这个问题)
public V put(K key, V value) {
K k = maskNull(key);
int hash = hash(k);
int i = indexFor(hash, table.length);
for (Entry<K,V> e = table; e != null; e = e.next) {
if (e.hash == hash && eq(k, e.key)) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
modCount++;
addEntry(hash, k, value, i);
return null;
}
static boolean eq(Object x, Object y) {
return x == y || x.equals(y);
}
void addEntry(int hash, K key, V value, int bucketIndex) {
Entry<K,V> e = table[bucketIndex];
table[bucketIndex] = new Entry<K,V>(hash, key, value, e);
if (size++ >= threshold)
resize(2 * table.length);
}