Yield Return In Java

后端 未结 10 1228
春和景丽
春和景丽 2020-12-13 23:13

I\'ve created a linked list in java using generics, and now I want to be able to iterate over all the elements in the list. In C# I would use yield return insid

10条回答
  •  既然无缘
    2020-12-13 23:54

    You can return an anonymous implementation of Iterable. The effects are pretty pretty similar, just that this is a lot more verbose.

    public Iterable getStuff() {
        return new Iterable() {
    
            @Override
            public Iterator iterator() {
                return new Iterator() {
    
                    @Override
                    public boolean hasNext() {
                        // TODO code to check next
                    }
    
                    @Override
                    public String next() {
                        // TODO code to go to next
                    }
    
                    @Override
                    public void remove() {
                        // TODO code to remove item or throw exception
                    }
    
                };
            }
        };
    }
    

提交回复
热议问题