Java iterator over an empty collection of a parameterized type

后端 未结 7 1512
隐瞒了意图╮
隐瞒了意图╮ 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:15

    I'd go more along the lines of

    public Iterator iterator() {
        if (underlyingData == null)
            return Collections. emptyList().iterator();
        return underlyingData.iterator();
    }
    

    Just, handle the special case and return, then handle the normal case. But my main point is that you can avoid the assignment with

    Collections. emptyList().iterator();
    

提交回复
热议问题