Last active
April 28, 2025 20:02
-
-
Save thinkphp/42e09e1be00ea7e7e1db14be61b13f2c to your computer and use it in GitHub Desktop.
Exemplu Interfata Iterator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Iterator; | |
import java.util.NoSuchElementException; | |
public class Main implements Iterator<Integer> { | |
private int[] data; | |
private int index = 0; | |
public Main(int[] data) { | |
this.data = data; | |
} | |
@Override | |
public boolean hasNext() { | |
return index < data.length; | |
} | |
@Override | |
public Integer next() { | |
if (!hasNext()) { | |
throw new NoSuchElementException("No more elements"); | |
} | |
return data[index++]; | |
} | |
@Override | |
public void remove() { | |
throw new UnsupportedOperationException("remove not supported"); | |
} | |
public static void main(String[] args) { | |
int[] numbers = {10, 20, 30, 40}; | |
Main it = new Main(numbers); | |
while (it.hasNext()) { | |
System.out.println(it.next()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment