Search code examples
javaiteratorlistiterator

Can't understand: if (val == null ? it.next() == null : val.equals(it.next()))


I saw this code snippet on Java Tutorial Oracle, however, no matter how hard I have tried, I can't understand the if (val == null ? it.next() == null : val.equals(it.next())).

What is its function and how does it work?

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

Solution

  • It is equality check between val and it.next(). null.equals() will throw NullPointerException, so the condition is used to avoid that.

    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