How to implement iterator as an attribute of a class in Java

后端 未结 6 949
既然无缘
既然无缘 2020-12-17 04:19

let\'s say I have this simple MyArray class, with two simple methods: add, delete and an iterator. In the main method we can see how it is supposed to be used:



        
6条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-17 04:47

    EDIT: this does not work for arrays of primitive types: you could use Arrays for this:

    it = new Arrays.asList(arr).subList(start, end).iterator(); END OF EDIT

    If you really want to implement your own iterator, I would suggest an internal class in this scenario. This way you can access MyArray.this from myIterator.

    public class MyArray {
        ....
        private class myIterator implements Iterator{
            ....
        }
    }
    

提交回复
热议问题