Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/elixir/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 检查一个ArrayList是否包含与另一个ArrayList相同的元素_Java_Android Studio_Arraylist - Fatal编程技术网

Java 检查一个ArrayList是否包含与另一个ArrayList相同的元素

Java 检查一个ArrayList是否包含与另一个ArrayList相同的元素,java,android-studio,arraylist,Java,Android Studio,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&l

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

// 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));
}

这在一定程度上是通过突出显示
主列表
lowEight
中的值来实现的,但例如,如果数字7在
lowEight
中,并且在
主列表
中出现9次,它将突出显示所有9次。有没有办法将准确的对象从
主列表
移动到
分类列表
,然后移动到
lowEight
,然后使用一种方法来检查对象而不仅仅是值?

让我提供一个更简洁的示例来说明您的问题。让我们以以下代码为例:

ArrayList列表1=新的ArrayList(){
{
增加(5);
增加(5);
}
};
ArrayList list2=新的ArrayList();
list2.add(list1.get(0));
list1.forEach((i)->System.out.println(list2.contains(i));
输出为:

true
真的
但你会期望它是:

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

公共类MyInteger{
私人期末考试i;
公共MyInteger(整数i){
这个。i=i;
}
公共int toInt(){
返回i;
}
}
然后当我们在ArrayList代码中使用它时:

ArrayList列表1=新的ArrayList(){
{
添加(新的MyInteger(5));
添加(新的MyInteger(5));
}
};
ArrayList list2=新的ArrayList();
list2.add(list1.get(0));
list1.forEach((i)->System.out.println(list2.contains(i));
我们得到了我们的预期产出:

true
假的

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

感谢您花时间给出如此精彩的解释!我要试一试。Thanks@JamesSmith没问题!如果你对这个答案有任何疑问,请随时提问,如果这个答案最终对你有所帮助,请回来并将其标记为已接受。
// 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);
}