java - 我正确使用 list.remove 吗?

标签 java list object

假设我知道列表 SomeList 包含 thatObj。以下代码是否从 SomeList 中删除对 thatObj 的引用?

SomeClass el = (SomeClass) thatObj.clone();
SomeList.remove(el);

如果此方法以某种方式比较对象,则无法通过引用找到。直觉表明它应该使用 Object.equals,如果引用指向同一个对象,它会返回 true,因此此代码将不起作用。

如果没有,那么还有一个问题:如果没有引用但知道相关对象的所有成员,如何从列表中删除?

最佳答案

Can't find through the reference if this method compares objects somehow. Intuition suggests that it should use Object.equals which returns true if references point to the same object, hence this code will not work.

是的,你说得对。

If not then an additional question: how to remove from list if don't have the reference but know all the members of the object in question?

两种可能性:

  • 覆盖类中的 equals 方法,创建一个包含所有已知成员的新实例,然后调用移除将新创建的实例作为参数传递
  • 遍历列表中的所有对象,并删除其成员等于您拥有的值的对象

关于java - 我正确使用 list.remove 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19731779/

相关文章:

java - 第一次点击后禁用 JButton

Java 套接字 : Read/receive the same instance multiple times after change values: ObjectInputStream. readObject()

c++ - 在类的构造函数中创建对象是否有效?

Javascript 验证 - 检查字符串是否是正确的对象

java - Junit 想在一定时间后停止该方法

java - 如何在 Java 中创建 macOS 风格的蓝色默认按钮?

java - 检查数组中同一对象的多个实例

python - 如何从 Python 列表中删除重复的字典(带有嵌套的字典)?

python - 在不使用 Python 额外内存的情况下迭代时从列表中删除项目

java - 许可基于 Java Web 的应用程序