包含在HashSet <int []>()</int []>中

时间:2014-05-22 19:09:49

标签: android contains hashset

在android中我试图保存用户已经按下的网格。

我正在使用的代码剪辑是:

// private
private HashSet<int[]> PlayerSelectedHashField = new HashSet<int[]>();
private boolean collisionDetected = false;

在我正在使用的功能中

collisionDetected = PlayerSelectedHashField.contains(TmpPos); // -> Fail - not working
{doing something}
PlayerSelectedHashField.add(TmpPos); // int[] TmpPos - TmpPos is x y

.add函数按预期工作,但.contains总是返回false。 为什么它不起作用 - 我能做些什么呢?

2 个答案:

答案 0 :(得分:3)

public boolean contains(Object o) {
    return map.containsKey(o);
}

的containsKey:

public boolean containsKey(Object key) {
    return getNode(hash(key), key) != null;
}

getNode:

final Node<K,V> getNode(int hash, Object key) {
    Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
    if ((tab = table) != null && (n = tab.length) > 0 &&
        (first = tab[(n - 1) & hash]) != null) {
        if (first.hash == hash && // always check first node
            ((k = first.key) == key || (key != null && key.equals(k))))
            return first;
        if ((e = first.next) != null) {
            if (first instanceof TreeNode)
                return ((TreeNode<K,V>)first).getTreeNode(hash, key);
            do {
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    return e;
            } while ((e = e.next) != null);
        }
    }
    return null;
}

由于equals的{​​{1}}将执行arrays比较,因此无法正常工作,只有当它们指向同一个实例时才会返回true。

你的问题可以修复而不用==(比较两个数组元素而不是引用的方式)(可能有问题(至少对我而言)。我更喜欢一种简单的方法)

由于您保存了Arrays.equalsX坐标,因此只需创建课程Y

Point

然后使用public class Point { public final int X; public final int Y; public Point(int x, int y) { X = x; Y = y; } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj instanceof Point) { Point pObj = (Point) obj; return pObj.X == X && pObj.Y == Y; } return false; } @Override public int hashCode() { int result = X; result = 31 * result + Y; return result; } } 课程来保存Point分。

您可以使用Android Point

,而不是创建自定义点类

实施例

X, Y

答案 1 :(得分:0)

来自HashSet javadocs:

  

public boolean contains(Object o)

     

如果此set包含指定的元素,则返回true。更正式地,当且仅当此集合包含元素e时才返回true(o == null?e == null:o.equals(e))。

因此,通常情况下,如果您不知道在特定对象类型上调用equals时会发生什么,那么contains也可能无法按预期运行。如果该对象类型在程序中具有概念意义,那么为特定对象创建类绝对不是一个坏主意。如果这样做,您可以覆盖equals方法以确保其行为完全符合您的要求。

相关问题