Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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?

share|improve this question
    
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 5:12
add comment

2 Answers

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.

share|improve this answer
add comment

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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