【问题标题】:How to remove a point from HashSet<Point>如何从 HashSet<Point> 中删除一个点
【发布时间】:2014-06-07 16:02:21
【问题描述】:

我有一个 HashSet,我可以添加一些点,但删除对我不起作用。 我也试着做一个函数。 我该如何解决这个问题?

HashSet<Point> array= new HashSet<Point>();

// add some elements:
    array.add(new Point (pos[0],pos[1]));

// remove a element (is not working...)
array.remove(new Point (pos[0],pos[1]));


// tried also to make a function:

    private void removePoint(HashSet<Point> array, final int[] pos) {
            Point pTmp;
            Point rPos = new Point (pos[0],pos[1]);
            final Iterator<Point> it = array.iterator();

            while (it.hasNext()) {
                pTmp = it.next();
                if (pTmp.equals(rPos)){
                    it.remove(); 
                    break;
                }
            }
            return;
        }

【问题讨论】:

  • Point从何而来?即你确定比较两个 Point 实例比较 Point 坐标并且不使用默认的 Java 比较,它不会 (afaik) 返回 true ;新点(0, 1).equals(新点(0, 1)) .
  • @harism:来自:import android.graphics.Point;

标签: android hashset


【解决方案1】:

通常,当我看到没有从 Set 中删除某些内容的情况时,这是因为 hashCode 或 equals 没有正确实现。现在很明显,如果您使用的是 Java Point,我怀疑情况并非如此。如果您使用自己的“Point”类,则需要确保覆盖 hashCode 和 equals。

【讨论】:

    猜你喜欢
    • 2015-11-16
    • 1970-01-01
    • 1970-01-01
    • 2021-05-05
    • 2011-11-20
    • 2020-02-26
    • 1970-01-01
    • 1970-01-01
    • 2013-03-11
    相关资源
    最近更新 更多