比较两个列表
我想比较两个列表。由于我们使用 List
编写接口,因此它不会从 Object 类继承 equals
。我该怎么做?
I want to compare two lists. Since we code to interface using List
, which does not inherit the equals
from from the Object class. How do I do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
即使
List
接口不包含equals
方法,列表类可能(并且确实)仍然实现equals
方法。来自
AbstractList
上的 API 文档(例如ArrayList
、LinkedList
、Vector
继承):这同样适用于例如
toString
、hashCode
方法等。正如 @Pascal 在评论中提到的,List 接口提到了 equals 方法并在文档中声明了以下内容:
Even though the
List
interface does not contain anequals
method, the list-classes may (and does) still implement theequals
method.From the API docs on
AbstractList
(inherited by for instanceArrayList
,LinkedList
,Vector
):The same applies to for instance the
toString
,hashCode
method and so on.As @Pascal mentions in the comments, the List interface mentions the
equals
method and states the following in the documentation:这是通常的故事:你必须考虑“浅等于”和“深等于”。
从 java.lang.Object 获得的默认行为是“浅等于”。它将检查 list1 和 list2 是否是相同的引用:
如果您想要“深度等于”,请实例化任何扩展 AbstractList 的内容,例如 ArrayList。
It's the usual story: you have to consider "shallow equals" and "deep equals".
The default behavior that you get out of java.lang.Object is "shallow equals". It'll check to see if list1 and list2 are the same references:
If you want "deep equals", instantiate anything that extends AbstractList, such as ArrayList.
您仍然可以使用
等于
。所有对象都实现它,并且您的列表仍然是对象,并根据需要覆盖equals
。You can still use
equals
. All objects implement it, and your lists are still objects and overrideequals
as you need it.