DualHashBidiMap和getKey方法

时间:2016-04-22 09:18:42

标签: java apache-commons

我遇到了DualHashBidiMap和getKey方法的问题。

我使用的是Commons Collections 4.1

containsKey 方法对于特定的密钥返回true,但 getKey 方法对同一个密钥返回null;

Key Class有一个SuperClass,等于 hashcode 方法被覆盖,以匹配 id 属性。

主类

public class Main {

public static void main(String[] args) {
    // TODO Auto-generated method stub

    DualHashBidiMap<Observed, Object> map=new DualHashBidiMap<Observed,Object>();

    Task t66=new Task();
    t66.setId(66);
    map.put(t66, "Task66");

    Task tFetch=new Task();
    tFetch.setId(66);
    System.out.println("tFetch present:"+map.containsKey(tFetch));
    System.out.println("tFetch Object:"+map.getKey(tFetch));
   }
}

这是输出

tFetch present:true
tFetch Object:null

关键班

public class Task extends Observed{

public void m1(){
    System.out.println("Method called !!");
  }
}

Key SuperClass

public class Observed extends Observable{
private Integer id;

public Integer getId() {
    return id;
}

public void setId(Integer id) {
    this.id = id;
}

@Override
public boolean equals(Object obj) {
    boolean retValue=false;
    Observed t=(Observed) obj;
    if(t.getId().equals(this.getId())) retValue=true;
    return retValue;
}

@Override
public int hashCode() {
    int hash = 3;
    hash = 53 * hash + (this.getId() != null ? this.getId().hashCode() : 0);
    hash = 53 * hash + this.getId();
    return hash;
   }
}

Tnks to all ..

1 个答案:

答案 0 :(得分:0)

您正在尝试获取地图中不存在的值的键。可能是你想要做的如下

public class Main {

public static void main(String[] args) {
    // TODO Auto-generated method stub

    DualHashBidiMap<Observed, Object> map=new DualHashBidiMap<Observed,Object>();

    Task t66=new Task();
    t66.setId(66);
    map.put(t66, "Task66");

    Task tFetch=new Task();
    tFetch.setId(66);
    System.out.println("tFetch present:"+map.containsKey(tFetch));
    // to get the key related to an object
    System.out.println("tFetch Object:"+map.getKey("Task66"));
    // to get a value related to a key
    System.out.println("tFetch Object:"+map.get(tFetch));
   }
}
相关问题