2017-10-20 91 views
0

希望我能理解Guava中的HashMultimap的用途,因为如果我不这样做,我只会低估自己。HashMultimap番石榴Java,从关键值获取集合的问题

我想从一个特定的键,其中关键的是,像这样一类访问集合...

public class Coords { 

private int[] coords; 

public Coords() { 
    coords = new int[2]; 
} 

public Coords(int x, int y) { 
    coords = new int[] {x, y}; 
} 

public void set(int x, int y) { 
    coords = new int[] {x, y}; 
} 

public int x() { 
    return coords[0]; 
} 

public int y() { 
    return coords[1]; 
} 

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

    Coords o = (Coords) obj; 

    return Integer.compare(x(), o.x()) == 0 && 
      Integer.compare(y(), o.y()) == 0; 
} 

当我比较两个COORDS在它的阵列相同的整数值的对象,我成真。

当我使用键/值对使HashMultimap流行时,确实会得到一组唯一的键,但我没有收集到多个Item。即使我重写了Object中的equals()方法,我也得到了多个似乎完全相同的密钥。当我流行的地图...

HashMultimap<Coords, Item> items = HashMultimap.create(); 

     Item s = new Item(); 
     s.coords.set(0, 0); 
     Item w = new Item(); 
     w.coords.set(0, 0); 

     Item p = new Item(); 
     p.coords.set(1, 1); 

     items.put(s.coords, s); 
     items.put(w.coords, w); 
     items.put(p.coords, p); 

     Collection<Item> bucket = items.get(s.coords); 
     bucket.add(s); 
     items.putAll(s.coords, bucket); 

     bucket = items.get(w.coords); 
     bucket.add(w); 
     items.putAll(w.coords, bucket); 

     bucket = items.get(p.coords); 
     bucket.add(p); 
     items.putAll(p.coords, bucket); 

     for(Coords key : items.keySet()) { 
      System.out.println(key.x() + " " + key.y()); 
     } 

我得到的输出...

0 0 
1 1 
0 0 

我缺少什么?我错误地执行了某些事情吗?

+1

你也需要重写hashCode。您的equals方法永远不会被调用,因为相同的Coordinates对象具有不同的hashCode,因此被放入不同的桶中。 –

+1

public int hashCode(){return Arrays.hashCode(coords); } –

回答

0

感谢您的所有意见。在我发布这个问题后不久我就意识到我需要覆盖hashCode()方法。当然......

但我会解释一下,对于那些陷入这个问题的人,并不明白如何成功实现hashCode()。这个问题有答案非常相似,我的...

Does hashcode implementation of Java Arrays.hashcode() uniformly distribute

但是,我最终实现的hashCode()这样的...

@Override 
public int hashCode() { 
    int hash = 1; 
    for (int e : coords) 
     hash = 31 * hash + e; 

    return hash; 
} 

由于CPP初学者,我可以用Arrays.hashCode(),但只是想我会写出一些东西,以便我可以看到它的工作。所以我可以更好地理解该方法以及它的作用。