如果e == null为真,有人可以解释检查next == null的目的吗?
当e == null为假时,为什么我们需要检查e是否等于下一个?
最后一个问题,为什么方法检查e是否等于next,但如果为true则返回previousIndex?我以为它会返回nextIndex。
public int indexOf(E e) {
for (ListIterator<E> it = listIterator(); it.hasNext(); ){
if (e == null ? it.next() == null : e.equals(it.next()))
return it.previousIndex();}
// Element not found
return -1;
}
由于
答案 0 :(得分:1)
如果我们将?:
拉出if,我们可以单独查看它可能有所帮助
public int indexOf(E e) {
for (ListIterator<E> it = listIterator(); it.hasNext(); ) {
boolean test = (e == null ? it.next() == null : e.equals(it.next()) );
if (test)
return it.previousIndex();
}
// Element not found
return -1;
}
解开另一个舞台,请记住?:
本质上是一个if / else:
public int indexOf(E e) {
for (ListIterator<E> it = listIterator(); it.hasNext(); ) {
boolean test;
if (e == null)
test = ( it.next() == null );
else
test = ( e.equals(it.next()) );
if (test)
return it.previousIndex();
}
// Element not found
return -1;
}
我认为您现在可以看到代码实际正在做什么 - 如果e为null,它会将==
相等的值检查为null,但如果e不为null,我们可以调用{{1}安全地使用那种比较。
如果你仍然感到困惑,让我们再展开一次:
.equals()
如果您已经习惯了,public int indexOf(E e) {
for (ListIterator<E> it = listIterator(); it.hasNext(); ) {
boolean test;
if (e == null) {
if ( it.next() == null )
return it.previousIndex;
}
else {
{
if ( e.equals(it.next()) )
return it.previousIndex;
}
}
// Element not found
return -1;
}
内联测试更紧凑并且在许多情况下更加清晰。如果你不习惯它,那么从详细拼写出来开始更安全,然后一旦你知道逻辑完成你想要的东西就把它重写成紧凑的形式。
答案 1 :(得分:0)
此处IF
运行如下---如果e == null
为真,则评估it.next() == null
,否则评估e.equals(it.next())
。此评估的结果将确定IF
是否需要分支到then
(执行return
)或(如果有的话)else
基本上,if
需要一个真值来测试。在你的情况下,真值是来自三元组。它没什么神奇之处。 HTH
答案 2 :(得分:0)
此处的三元运算符用于执行null
- 安全等于检查。
有时,如果您不控制列表的内容,则需要进行此类检查,因为e.equals(obj)
为e
时您无法使用null
。
如果List不返回null
值,那就更好了。
为了弄清楚它我们能否重构它。
在第一步中,我们通过方法调用替换if语句的表达式。
因为我们不知道它的作用,我们称之为foo
方法,我们稍后会重命名它。它将返回boolean
并为E
提取两个类型为e
的参数,为it.next()
提取一个参数。
重构后,它看起来像:
public int indexOf(E e) {
for (ListIterator<E> it = listIterator(); it.hasNext(); ){
if (foo(e, it.next())
return it.previousIndex();}
// Element not found
return -1;
}
public boolean foo(E e, E next) {
// in the first step we take the expression as it is
return e == null ? next == null : e.equals(next);
}
然后我们将?:
运算符拆分为if
else
语句
public boolean foo(E e, E next) {
if (e == null)
return next == null;
else
return e.equals(next);
}
现在我们看看它做了什么。如果传递的元素e
为null
,则会检查next
是否也是null
,在这种情况下,它会返回true
,否则会返回false
。< / p>
如果e
本身不是null
,则会使用e
的{{1}}方法将next
与equals
进行比较。
所以这是一个空安全或空知识等于比较。
我们现在知道了它的作用后,我们将E
重命名为有用的内容,例如foo
etvoilà
isEqual
答案 3 :(得分:-1)
是的,但我会像这样写
for (ListIterator<E> it = listIterator(); it.hasNext(); ){
if (e == null ? it.next() == null : e.equals(it.next())) {
return it.previousIndex();}
} else {
return -1;
}
}