我目前有一个对象的 List
。通过以下方式删除对象:
if (mProducts.contains(orderProduct)) {
mProducts.remove(orderProduct);
.
.
然而 List
的 javadocs 状态
Removes the first occurrence of the specified object from this {@code List}.
我需要从列表中删除 given 对象,而不仅仅是第一个对象。这里正确的方法是什么?我可以提供自己的 List.remove 实现或使用替代数据结构吗?
谢谢, 奥特曼
最佳答案
在 Java 中,List 使用 equals() 作为它的 contains 和 remove(Object o) 方法,如 here 所述
在其中一个答案评论中还指出,Java 默认使用引用比较。
也许您可以重写产品的 equals() 方法以获得您想要的结果。
关于java - 替代列表数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42209313/