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’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
.
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.