Iterable vs Iterator in Java

List<Integer> integers = new ArrayList<>(Arrays.asList(1, 2, 3));

for (Integer number : integers) {
System.out.println(number);
}
Iterator<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5).iterator();
while (numbers.hasNext()) {
System.out.println(numbers.next());
}
public class CustomIterable<T> implements Iterable<T> {
List<T> values = new ArrayList<>();

public void add(T value) {
values.add(value);
}
@Override
public Iterator<T> iterator() {
return new CustomIterator<T>(values);
}

public class CustomIterator<E> implements Iterator<E> {

List<E> data;
int position = 0;

public CustomIterator(List<E> data) {
this.data = data;
}

@Override
public boolean hasNext() {
return data.size() > position + 1;
}

@Override
public E next() {
E nextValue = this.data.get(position);
position++;
return nextValue;
}
}
}
public static void main(String[] args) {
CustomIterable<Integer> integers = new CustomIterable<>();
integers.add(1);
integers.add(2);
integers.add(3);
integers.add(4);
integers.add(5);

for (Integer integer : integers)
System.out.println(integer);
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store