【问题标题】:Check if an ArrayList contains the same element as another ArrayList检查一个 ArrayList 是否包含与另一个 ArrayList 相同的元素
【发布时间】:2021-01-03 17:50:13
【问题描述】:

我使用了其他一些答案来解决我的问题。但我想知道是否有办法进一步改进?

// Copy the masterList ArrayList and then sort in ascending order and then make a third 
// ArrayList and loop through to add the 8 lowest values to this list.
ArrayList<Integer> sortedList = new ArrayList<>(Calculator.masterList);
Collections.sort(sortedList);
ArrayList<Integer> lowEight = new ArrayList<>();
for (int i = 0; i < 8; i++) {
    lowEight.add(sortedList.get(i));
}
// Set TextView as the value of index 0 in masterList ArrayList, check if lowEight 
// ArrayList contains the element that is the same as masterList index 0 and if
// so highlight s1 textview green.
s1.setText("Score 1 is " + String.format("%d", Calculator.masterList.get(0)));
if (lowEight.contains(Calculator.masterList.get(0))) {
    s1.setBackgroundColor(Color.GREEN);
}

这在一定程度上通过突出显示masterListlowEight 中的值来起作用,但例如,如果数字7 在lowEight 中并且在masterList 中出现9 次,它将突出显示所有9 个出现。有没有办法将确切的对象从masterList 移动到sortedList,然后到lowEight,然后有一种方法来检查对象而不仅仅是值?

【问题讨论】:

    标签: java android-studio arraylist


    【解决方案1】:

    让我提供一个更简洁的示例来说明您的要求。让我们看下面的代码:

    ArrayList<Integer> list1 = new ArrayList<Integer>() {
        {
            add(5);
            add(5);
        }
    };
    
    ArrayList<Integer> list2 = new ArrayList<>();
    list2.add(list1.get(0));
    list1.forEach((i) -> System.out.println(list2.contains(i)));
    

    输出是:

    true
    true
    

    但你会期望它是:

    true
    false
    

    因为第一个和第二个元素是不同的对象。这里的问题是,虽然它们是 不同 对象,但它们是 相等 对象。 Integer 类是用 Java 编写的,如果它们表示相同的值,则任何 Integer 都等于另一个 Integer。当您运行contains() 方法时,它会看到列表确实包含一个与您提供的对象相等的对象(在这种情况下,它们都表示值5),因此它返回true。那么我们如何解决这个问题呢?我们如何区分一个 Integer 对象和另一个?我会写你自己的“整数”类。像“MyInteger”这样的东西。这是您可以使用的一个非常简单的实现:

    public class MyInteger {
        private final int i;
    
        public MyInteger(int i) {
            this.i = i;
        }
    
        public int toInt() {
            return i;
        }
    }
    

    然后当我们在 ArrayList 代码中使用它时:

    ArrayList<MyInteger> list1 = new ArrayList<MyInteger>() {
        {
            add(new MyInteger(5));
            add(new MyInteger(5));
        }
    };
    
    ArrayList<MyInteger> list2 = new ArrayList<>();
    list2.add(list1.get(0));
    list1.forEach((i) -> System.out.println(list2.contains(i)));
    

    我们得到了预期的输出:

    true
    false
    

    这是因为我们的新 MyInteger 类隐式使用默认的 equals() 方法,该方法总是返回 false。换句话说,没有两个 MyInteger 对象永远相等。您可以将同样的原则应用到您的代码中。

    【讨论】:

    • 感谢您抽出宝贵的时间给出很好的解释!我会试一试。谢谢
    • @JamesSmith 没问题!如果您对这个答案有任何疑问,请随时提问,如果这个答案最终对您有所帮助,请返回并将其标记为已接受。
    猜你喜欢
    • 1970-01-01
    • 2013-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-26
    • 2012-05-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多