无法理解:if(val == null?it.next()== null:val.equals(it.next()))

时间:2016-03-13 02:14:27

标签: java iterator listiterator

我在Java Tutorial Oracle上看到了这段代码,然而,无论我多么努力,我都无法理解if (val == null ? it.next() == null : val.equals(it.next()))

它的功能是什么?它是如何工作的?

public static <E> void replace(List<E> list, E val, E newVal) {
    for (ListIterator<E> it = list.listIterator(); it.hasNext(); )
        if (val == null ? it.next() == null : val.equals(it.next()))
            it.set(newVal);
}

2 个答案:

答案 0 :(得分:2)

valit.next()之间的平等检查。 null.equals()将抛出NullPointerException,因此使用该条件来避免这种情况。

if ( // the if statement
    val == null ? // let me name this "condition A"
        it.next() == null : // this will be evaluated if condition A is true
        val.equals(it.next()) // this will be evaluated if condition A is false
) // the if statement

答案 1 :(得分:-1)

此代码尝试在列表中找到val,然后将其替换为newVal

for (ListIterator<E> it = list.listIterator(); it.hasNext();)
        if (val == null && it.next() == null)
        { }
        else if val.equals(it.next()))
            it.set(newVal);