使用带有对象的hashmap作为键

时间:2015-05-11 07:09:16

标签: java object hashmap key

我尝试使用带有对象键的hashmap。 我可以填写hashmap。我可以用nbrCheminHashInter.keySet显示haskmap的内容。但是不可能得到一个,我总是得到一个空值。你能帮帮我吗?

public class MyKey<V> {
 private V u;
private V v;
private V i;

// Constructor MyKey
public MyKey(V i,V u,V v){
this.i=i; 
this.u=u;
this.v=v;
}

...
public String toString(){
     return ""+this.i+""+this.u + ""+ this.v ;
 }
}

for(V i:listeSommet){
 for(V u:listeSommet){
  for(V v:listeSommet){
   nbrCheminHashInter.put(new MyKey<V>(i,u,v),0.0);}}}

  //Print key and value
 for(MyKey<V> key :nbrCheminHashInter.keySet() ){
           System.out.println("Cle "+key+" value     "+nbrCheminHashInter.get(key));
       }
 //print always null           
 for(V i:listeSommet){
  for(V u:listeSommet){
   for(V v:listeSommet){
  System.out.println(nbrCheminHashInter.get(new MyKey<V>(i,u,v));
    }
   }
  }

2 个答案:

答案 0 :(得分:0)

您需要覆盖hashcode并等于

 public class MyKey<V> {
  private V u;
  private V v;
  private V i;

  // Constructor MyKey
  public MyKey(V i,V u,V v){
    this.i=i;
    this.u=u;
    this.v=v;
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    MyKey myKey = (MyKey) o;

    if (i != null ? !i.equals(myKey.i) : myKey.i != null) return false;
    if (u != null ? !u.equals(myKey.u) : myKey.u != null) return false;
    if (v != null ? !v.equals(myKey.v) : myKey.v != null) return false;

    return true;
  }

  @Override
  public int hashCode() {
    int result = u != null ? u.hashCode() : 0;
    result = 31 * result + (v != null ? v.hashCode() : 0);
    result = 31 * result + (i != null ? i.hashCode() : 0);
    return result;
  }

  public String toString(){
    return " "+this.i+" "+this.u + " "+ this.v ;
  }

  public static void main(String[] args) {
    HashMap<MyKey<String>,Double> map = new HashMap<MyKey<String>, Double>();
    map.put(new MyKey<String>("foo","bar","something"),2.1);
    map.put(new MyKey<String>("foo2","bar2","something2"),2.2);

    for (Map.Entry<MyKey<String>, Double> entry : map.entrySet()){
      System.out.println("key is: " + entry.getKey());
      System.out.println("Value is: " + entry.getValue());
    }
    System.out.println("test");
    System.out.println(map.get(new MyKey<String>("foo", "bar", "something")));
  }
}

答案 1 :(得分:0)

从Object继承的hashCode的默认实现返回对象在RAM中的地址。

当您尝试通过get(new MyKey())从HashMap获取值时,会创建一个新对象,并且地图中没有相应的键,并且RAM中有此地址。

在MyKey类中覆盖int hashCode()boolean equals(Object other)

另一种解决方案是:

for(MyKey<V> m : map.keySet()){
    println(map.get(m);
}

这样可行,因为您正在处理RAM中相同位置的相同对象

相关问题