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



我在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);
}

它是 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

此代码尝试在列表中查找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);

最新更新