[英]Check if an ArrayList contains every element from another ArrayList (or Collection)
[英]Check if an ArrayList contains the same element as another ArrayList
我使用了其他一些答案来解决我的问题。 但我想知道是否有办法进一步改善这一点?
// 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);
}
这通过突出显示是在两个值工作的程度masterList
和lowEight
但例如如果数字7是lowEight
并显示在9倍masterList
它将突出显示所有9个OCCURENCES。 有没有办法将确切的对象从masterList
移动到sortedList
,然后移动到lowEight
,然后是一种检查对象而不仅仅是值的方法?
让我提供一个更简洁的示例来说明您的要求。 让我们使用以下代码:
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 对象永远相等。 您可以将同样的原则应用到您的代码中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.