假设我知道列表 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/