Advertisement
desislava_topuzakova

02.Collection -> ListyIterator

Oct 16th, 2020 (edited)
564
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.29 KB | None | 0 0
  1. package Collection_02;
  2.  
  3. import java.util.Iterator;
  4. import java.util.List;
  5.  
  6. public class ListlyIterator implements Iterable<String> {
  7.     private List<String> data;
  8.     private int index;
  9.  
  10.     public ListlyIterator(List<String> data){
  11.         this.data = data;
  12.         this.setIndex(index);
  13.     }
  14.  
  15.     private void setIndex(int index){
  16.         if (this.data.size() == 0){
  17.             this.index = -1;
  18.         }else{
  19.             this.index = 0;
  20.         }
  21.     }
  22.  
  23.     public boolean move(){
  24.         if(this.index < this.data.size() - 1){
  25.             this.index++;
  26.             return true;
  27.         }
  28.  
  29.         return false;
  30.     }
  31.  
  32.     public String print(){
  33.         if(this.index != -1){
  34.             return this.data.get(this.index);
  35.         }
  36.         return "Invalid Operation!";
  37.     }
  38.  
  39.     public boolean hasNext(){
  40.         return this.index < this.data.size() - 1;
  41.     }
  42.  
  43.     @Override
  44.     public Iterator<String> iterator() {
  45.         return new Iterator<>() {
  46.             private int index = 0;
  47.             @Override
  48.             public boolean hasNext() {
  49.                 return this.index <= data.size() - 1;
  50.             }
  51.  
  52.             @Override
  53.             public String next() {
  54.                 return data.get(this.index++);
  55.             }
  56.         };
  57.     }
  58. }
  59.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement