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?

  • it.next() == null is an expression, val.equals(it.next())) is an expression. If val == null, evaluate the former, else evaluate the latter. – Ismail Badawi Jul 24 '13 at 05:12

2 Answers2

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.

Frank
  • 14,427
  • 3
  • 42
  • 67
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.

jmoreno
  • 10,853
  • 1
  • 31
  • 48