0

I have an issue with the DualHashBidiMap and getKey method.

I'm using Commons Collections 4.1

The containsKey method returns true for specific key insterted, but getKey method returns null for the same key;

Key Class have a SuperClass with equals and hashcode method overrided to match by id property.


Main Class

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));
   }
}

this is the output

tFetch present:true
tFetch Object:null

Key Class

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

Max
  • 25
  • 5

1 Answers1

0

You are trying to get key for a value that doesn't exist in the map. May be you want to do as below

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));
   }
}
awsome
  • 2,143
  • 2
  • 23
  • 41
  • Ok, now i understood. I thought that getKey method returned Key Object by key value. Sorry for the mistake and thanks for the explanation. – Max Apr 22 '16 at 12:18
  • If this answers your question, then mark it as the answered so that other unanswered questions get the attention needed – awsome Apr 22 '16 at 13:06