0

could you please help me understand this ternary operator

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

i thought the part after ? is just a regular statement, so how is == being used here?

1
  • it.next() == null is an expression, val.equals(it.next())) is an expression. If val == null, evaluate the former, else evaluate the latter. Commented Jul 24, 2013 at 5:12

2 Answers 2

3

It's very easy to see, once you start to pull out the expression into a separate variable:

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

I intentionally left the type as T. When you think about what type it has to be, the answer to your question appears: As the variable is used as the condition of an if-expression, it must be a boolean type, and hence, it is clear, what it.next() == null is doing here.

You just happened to run into the case where a ? b : c has three elements a,b,c which are all of type boolean.

1

It is a normal EXPRESSION, which in this case returns a boolean. It is the equivalent of:

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

A ternary expression returns a value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.