In Java, I need to return an Iterator from my method. My data comes from another object which usually can give me an iterator so I can just return that, but in some circums
I guess this shows that Java type inference doesn't work in every case and that the ternary operator is not always equivalent to the apparently equivalent if-else construct.
I also want to state avoid null. Also avoid passing Iterators about, because they have strange stateful behaviour (prefer Iterable). However, assuming you have a legitimate, non-premature reason for doing this, my preferred way of writing it would be
public Iterator iterator() {
return getUnderlyingData().iterator();
}
private List getUnderlyingData() {
if (underlyingData == null) {
return Collections.emptyList();
} else {
return underlyingData;
}
}
IMO, it's better not to insert the inferable type information if it can be inferred (even if it makes your code longer).
You are almost certainly going to do it more than once, so insert a getUnderlyingData method instead of just declaring a local variable.
You are calling iterator on both results, so do not repeat yourself.