Java iterator over an empty collection of a parameterized type

后端 未结 7 1650
隐瞒了意图╮
隐瞒了意图╮ 2021-01-03 18:36

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

7条回答
  •  我在风中等你
    2021-01-03 19:09

    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.

提交回复
热议问题