【问题标题】:two equal array lists but java does not see equal [duplicate]两个相等的数组列表,但java看不到相等[重复]
【发布时间】:2014-04-24 08:07:45
【问题描述】:

这里我声明了两个数组列表

ArrayList<Location> possibleMoves = new ArrayList<Location>();
possibleMoves.add(new Location(0, 1));
possibleMoves.add(new Location(1, 0));

ArrayList<Location> possibleMoves1 = new ArrayList<Location>();
possibleMoves1.add(new Location(0, 1));
possibleMoves1.add(new Location(1, 0));

很明显这两个数组列表是相同的,但是当我运行这个检查时,它似乎总是失败。

if(possibleMoves == possibleMoves1){
  System.out.println("lol");
}

我也试过了,失败了

assertTrue("Player 1 1st piece could play to the left and down!",
arrayListsEqual(possibleMoves, possibleMoves1));

这是arrayListsEqual的方法

private boolean arrayListsEqual(ArrayList<Location> a, ArrayList<Location> b) {
    if (a.size() != b.size()) {
        return false;
    }
    int size = a.size();
    boolean thisOneFound = false;
    for (int i = 0; i < size; i++) {
        thisOneFound = false;
        for (int j = 0; j < size; j++) {
            if (a.get(i).equals(b.get(j))) {
                thisOneFound = true;
                break;
            }
        }
        if (!thisOneFound) {
            return false;
        }
    }
    return true;
}

【问题讨论】:

  • arrayListsEqual 定义在哪个库中?
  • @Duncan 它在课程教授制作的测试文件中给出
  • @user3567826 请告诉我们arrayListsEqual的定义。
  • @Duncan 我已将其添加到帖子中
  • @user3567826 有趣 - 相等方法不关心列表中项目的顺序。多么奇怪。

标签: java eclipse arraylist junit


【解决方案1】:

2 个问题:

  1. “位置”对象是不同的实例。所以它们是完全不相关的对象。
  2. 列表本身就是不同的实例。

首先:您需要使用列表的“equals”方法检查是否相等:

 list1.equals(list2).

此外,您需要确保将 SAME 对象保存在这些列表中(通过使用相同的实例)或在“Location”类中实现“equals”和“hashmap”方法。

一旦完成,它应该可以工作。

祝你好运:)

【讨论】:

  • 我明白这一点,但不幸的是我无法修改这个 assertTrue("Player 1 第一件可以向左和向下播放!", arrayListsEqual(possibleMoves, possibleMoves1));它在教授创建的测试文件中给出,所以我应该使用 assertListsEqual
  • @user3567826 在这种情况下,您唯一的要求是在您的Location 类中实现equals()hashCode
  • @Duncan 你是对的!!错过这个真是太愚蠢了!谢谢,我想当你保持清醒 2 天工作时,你会想念一些小东西:D
【解决方案2】:

请阅读==equals 之间的区别。 == 检查两个引用是否引用同一个实例,而 equals 测试是否相等。看看这个question的答案。

【讨论】:

    【解决方案3】:

    您不能将引用对象与 == 进行比较,ArrayList 不是原始数据类型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-17
      • 1970-01-01
      • 2016-02-21
      • 2012-02-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多