public class C1 implements Iterable { private LinkedList list; public static class NC1 { ... } ... x public Iterator iterator() { return list.iterator(); } }
but eclipse whines (at the x-ed line):
- The return type is incompatible with Iterable<NC1>.iterator()
- implements java.lang.Iterable<NC1>.iterator
I don't understand where the mistake is. Can someone help?
The Iterable interface was introduced in JDK 1.5. It belongs to java. lang package. In general, an object Implementing Iterable allows it to be iterated. An iterable interface allows an object to be the target of enhanced for loop(for-each loop).
Iterable Interface Definition The method you must implement is named iterator() . This method must return a Java Iterator which can be used to iterate the elements of the object implementing the Iterable interface.
Iterator is implemented by concrete classes Like ArrayList,Vector,LinkedList,HashSet,TreeSet because order and the way iterator is done depends on the concrete class type.
Iterator is an interface, which has implementation for iterate over elements. Iterable is an interface which provides Iterator.
You need to change NC1
to C1.NC1
. The following compiles:
import java.util.*;
public class C1 implements Iterable<C1.NC1> {
private LinkedList<NC1> list;
public static class NC1 {
}
public Iterator<C1.NC1> iterator() {
return list.iterator();
}
}
Alternatively, you could import static yourpackage.C1.NC1
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With