For educational purposes, it was necessary to independently implement linked lists and make it possible to bypass through foreach. As I understand it, you need to implement Iterable in the collection and create a class implementing Iterator. The question is what exactly to do in the Iterable interface method.

public void forEach(Consumer action) 

and Iterator interface method

  public void forEachRemaining(Consumer<? super E> action) throws NullPointerException 
  • In Iterable you need, of course, to implement an iterator() method that returns - what? - iterator. - VladD
  • This is yes, but I’m talking about forEach (Consumer action) writing - mcstarioni
  • one
    you can do nothing, Iterable.forEach and Iterator.forEachRemaining are default methods, i.e. they have an implementation in the interface (the help describes the expected behavior). - zRrr

1 answer 1

Since Java specialists are not responding, and @Barmaley has not yet returned , I will try to write.

 public class MyLinkedList<T> implements Iterable<T> { // имплементация вашего класса public Iterator<T> iterator() { return new MyLinkedListIterator(); } private class MyLinkedListIterator implements Iterator<T> { private MyListNode curr; public MyLinkedListIterator() { this.curr = MyLinkedList.this.head; // голова списка } public boolean hasNext() { return this.curr != null; } public T next() { if (!this.hasNext()) { throw new NoSuchElementException(); } T value = curr.value; // значение в текущем узле curr = curr.next; // следующий узел return value; } public void remove() { throw new UnsupportedOperationException(); } } } 

You don’t need to do anything else, it compiles. Now you can write:

 MyLinkedList<Integer> l = new MyLinkedList<>(); for (Integer v : l) { System.out.println(v); } 
  • A type conversion error appears, requires Object for (Object o: list) {System.out.println (o); } - mcstarioni
  • @mcstarioni: I compile: ideone.com/E6OTTG - VladD
  • I found an error, when declaring an iterator class, I put another <T>. - mcstarioni