【问题标题】:java-contains but with specific parametersjava-包含但具有特定参数
【发布时间】:2015-01-14 05:25:37
【问题描述】:

我对 java 中的“包含”方法有疑问。 我有对象 Tile,它包括 int x、int y(坐标)和字符串。 我想将对象添加到队列中,没有重复。 当我说重复时,我的意思是坐标。我不关心字符串。

但是当我写这样的东西时:

for (Tile x : neighbours)
{
    if (!queue.contains(x))
        queue.add(x);
}

它是全部加起来,我猜他看到一个参数不相等(字符串) 因此,他将 x 放入队列中。

你知道我如何仅根据坐标将新对象放入队列中吗? 两个坐标相同但字符串不同的对象对我来说是同一个对象。

谢谢...

【问题讨论】:

  • queue的类型是什么?
  • Tileequals方法是如何实现的?

标签: java collections contains


【解决方案1】:

要检查与属性匹配的元素,而不是相等,使用循环可能是最简单的。但是,如果您想使用单个方法,可以将 lambda 作为谓词传递给anyMatch

for (Tile x : neighbours) {
    if (!queue.stream().anyMatch(t -> x.x == t.x && x.y == t.y)) {
        queue.add(x);
    }
}

【讨论】:

    【解决方案2】:

    我已经做了这个功能。我虽然有一个简短的“魔法”。

    public static boolean containsCoordinates (LinkedList<Tile> queue, Tile obj)
    {
        for (Tile queueTile : queue)
        {
             if (queueTile.getX()==obj.getX())
             {
                 if (queueTile.getY()==obj.getY())
                     return true;
             }
        }
    
        return false;
    }                
    

    还是谢谢....

    【讨论】:

      【解决方案3】:

      如果你想使用一些“魔法”,那么你可以考虑以下测试:

      for (Tile x : neighbours) {
          if (!queue.contains(new Object() {
              public boolean equals(Object t) {
                  return x.x == ((Tile) t).x && x.y == ((Tile) t).y;
              }
          })) {
              queue.add(x);
          }
      }
      

      我没有将给定的 Tile t 传递给 contains 方法,而是将 Object 实例传递给重写的 equals 方法。这是可行的,因为contains 接受任何类型的对象。

      从程序逻辑来看,这个版本相当于@Joe给出的答案

      【讨论】:

        【解决方案4】:

        来自java.util.Collection 的文档(它定义了contains 方法并且是队列的超接口):

        boolean contains(Object o)

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

        所以覆盖Titleequals 方法以满足您的需求。例如

        class Tile {
            ...
            @Override
            public boolean equals(Object o) {
                if (o == null || !(o instanceof Title)) {
                    return false;
                }
                if (this == o) {
                    return true;
                }
                return this.x == o.x && this.y == o.y;
            }
            ...
        }
        

        Eclipse 或 IntelliJ Idea 等 IDE 能够生成 equalshashCode 方法(当您覆盖其中一个时,您也应该始终覆盖另一个)。

        【讨论】:

        • 我已经做了这个功能。我虽然有一个简短的“魔法”。 public static boolean containsCoordinates (LinkedList queue, Tile obj) { for (Tile queueTile : queue) { if (queueTile.getX()==obj.getX()) { if (queueTile.getY()==obj. getY()) 返回真; } } 返回假; } 无论如何谢谢....
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-04-07
        • 2023-03-24
        • 1970-01-01
        • 1970-01-01
        • 2012-07-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多