我想知道是否有一种方法可以连续比较2个ArrayList,直到它们的大小相同或元素相同。第一个 ArrayList 将具有一组固定的元素(假设有 5 个元素)。第二个 ArrayList 将为空,每次用户交互时都会将一个元素添加到第二个 ArrayList 中。当第二个 ArrayList 与第一个 ArrayList 的大小相同时,将进行比较以查看两个 arrayList 是否相同。
我尝试了多种方法来做到这一点:
我使用嵌套循环来比较存储和播放的项目
public int compare(ImageView computer, ImageView player){ if(player == computer) return 1; else return 2; } public void checkMatch(){ for(int x = 0; x < storedList.size(); x++){ for(int y = 0; y < playedList.size(); y++){ result = compare(storedList.get(x), playedList.get(y)); if(result == 1) //Do stuff else //End round } } }
然后我只是尝试明确地执行此操作
if(playedList == storedList) //do stuff else //do stuff
所有这些都可能有效,但我不知道在哪里调用它,以便代码真正等待所有用户输入完全完成。预先感谢您的帮助。
最佳答案
对您的代码进行一些评论:
if(playedList == storedList)
不会做你期望的事情。 == 仅当引用相同时才为 true,而当对象相等时则不然。您应该使用 if(storedList.equals(playedList))
来代替。
我不确定您是否需要首先检查大小(无论如何都是在 equals 方法中完成的),并且没有代码会更干净。
关于java - 连续比较2个ArrayList的大小和元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30161572/