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

后端 未结 6 952
既然无缘
既然无缘 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:44

    Iterator is an interface . Iterator which means only Object can go here (E) . Iterator is legal but Integer is not because int is primitive data type

    You can change the array to the ArrayList and then iterate over this arraylist. I added getIterator() method that returns the arraylist.iterator() and test it in main() method

    import java.util.ArrayList;
    import java.util.Iterator;
    
    public class MyArray {
     int start;
     int end;
     ArrayList arr;
    
    
     public MyArray() {
      this.start = 0;
      this.end = 0;
      arr = new ArrayList(500);
     }
    
     public void add(int el) {
      arr.add(el);
      this.end++;
     }
    
     public void delete() {
      arr.remove(arr.size()-1);
      this.start++;
     }
    
     public Iterator getIterator(){
      return arr.iterator();
     }
    
     public static void main(String[] args) {
      MyArray m = new MyArray();
    
      m.add(3);
      m.add(299);
      m.add(19);
      m.add(27);
    
      Iterator it = m.getIterator();
    
      while(it.hasNext()){
       System.out.println(it.next());
      }
    
     }
    
    }
    

提交回复
热议问题