HashMap rehashing会处理修改后的密钥吗?

时间:2015-12-05 11:43:41

标签: java hashmap

我已经编写了一个示例程序来测试它。我添加了一些键值对并更改了其中一个键,之后我插入了一些超过阈值的键值对。所以应该进行重复,当我用改变的键查找理想情况时,我应该得到正确的值。但我没弄错。有人可以在我失踪的地方帮助我吗?

public class HashMapTest {

public static void main(String[] args) {

    Map<Employee, String> map = new HashMap<Employee, String>();
    Employee obj = null;

    for(int i=1; i< 5; i++) {
        Employee emp = new Employee();
        emp.setId(i);
        emp.setName("vamsi"+i);         
        map.put(emp, emp.getName());
        if(obj == null && i == 3) {
            obj = emp; 
            System.out.println(obj.hashCode());
        }
    }

    System.out.println("Before changing the key: "+map.get(obj));
    obj.setId(15);
    System.out.println(hash(obj.hashCode()));
    for(int i=20; i< 45; i++) {
        Employee emp = new Employee();
        emp.setId(1+i);
        emp.setName("vamsi"+i);         
        map.put(emp, emp.getName());
    }
    System.out.println("After changing the key: "+map.containsKey(obj));
    Set<Map.Entry<Employee, String>> ent = map.entrySet();
    for(Map.Entry<Employee, String> ent1 : ent) {
        System.out.println(ent1.getValue()+ " " +ent1.getKey().hashCode());

    }       
}

public void capacityTest() {
    HashMap<String, String> map = new HashMap<String, String>();
    map.put("vamsi", "vamsi");

    for(int i=1; i< 14; i++) {
        map.put("vamsi"+i, "vamsi");
    }

    System.out.println(map.size());
}

static int hash(int h) {  
    h ^= (h >>> 20) ^ (h >>> 12); 
    return h ^ (h >>> 7) ^ (h >>> 4);  
  }
}


class Employee {

private int id;
private String name;

public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
@Override
public int hashCode() {     
    int result = 1;
    result = 2 * id * name.hashCode();
    return result;
}
@Override
public boolean equals(Object obj) {
            Employee other = (Employee) obj;
     if (id != (other.id))
        return false;
    if (name == null) {
        if (other.name != null)
            return false;
    } else if (!name.equals(other.name))
        return false;
    return true;
  }
}                    

1 个答案:

答案 0 :(得分:2)

在Java 8中,Employee.hashCode()被缓存。

// from the source for HashMap.Node
static class Node<K,V> implements Map.Entry<K,V> {
    final int hash;
    final K key;
    V value;
    Node<K,V> next;

这意味着如果您更改对象中的hashCode,它将在数据结构中实际更改,直到您将其删除(成功)并将其重新添加。