[英]why these two lists are not equal?
I was ask this java question in an interview: 我在一次采访中问这个Java问题:
List a = new ArrayList();
a.add(a);
List b = new ArrayList();
b.add(b);
if (a.equals(b)) {
System.out.println("equal");
} else {
System.out.println("non-equal");
}
why the result is 'non-equal' ? 为什么结果是“不相等”? thanks! 谢谢!
Your code (after the edit) results in StackOverflowException
because a
contains itself and b
contains itself. 您的代码(编辑后)将导致StackOverflowException
因为a
包含自身, b
包含自身。
a.equals(b)
will iterate the lists in parallel and compare each element, so a.get(0).equals(b.get(0))
, but a.get(0)
is a
and b.get(0)
is b
and comparing those will recurse the equals
method, ad infinitum. a.equals(b)
将并行迭代列表并比较每个元素,因此a.get(0).equals(b.get(0))
,但a.get(0)
是a
和b.get(0)
是b
,比较它们将递归equals
方法,无穷。
List a = new ArrayList();
a.add(a);
List b = new ArrayList();
a.add(b);
Look carefully. 仔细地看。 a has now two items (a and b) and b has no items. a现在有两个项目(a和b),而b没有项目。 So a is not equal to b. 因此a不等于b。
[THIS ANSWER REFERS TO THE POST BEFORE THE EDIT] [此答复在编辑前引用该帖子]
The .equals
method compares the content of the two array lists. .equals
方法比较两个数组列表的内容。 (Not if they are the same object) (如果它们是同一对象,则不是)
If you look carefully after you use the method .add
, the List a
has two elements ( a
and b
), instead of b
which has nothing 如果在使用.add
方法后仔细.add
,则列表a
具有两个元素( a
和b
),而不是b
没有任何元素
The code doesn't go in java.lang.StackOverflowError
, because the .equals
method checks first the size of the two lists, and then the content. 该代码不会放入java.lang.StackOverflowError
,因为.equals
方法首先检查两个列表的大小,然后检查内容。
In fact if you try this code: 实际上,如果您尝试以下代码:
List a = new ArrayList();
a.add(a);
List b = new ArrayList();
b.add(b); // <-watch carefully here. Now a and b are of the same size
if (a.equals(b)) { // checks the size first, then the objects in the lists
System.out.println("equal");
} else {
System.out.println("non-equal");
}
you get the java.lang.StackOverflowError
你得到java.lang.StackOverflowError
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.