希望我能理解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
我缺少什么?我错误地执行了某些事情吗?
你也需要重写hashCode。您的equals方法永远不会被调用,因为相同的Coordinates对象具有不同的hashCode,因此被放入不同的桶中。 –
public int hashCode(){return Arrays.hashCode(coords); } –