Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing the Java Iterable<E> interface

Tags:

java

iterable

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?

like image 404
Metz Avatar asked May 31 '10 13:05

Metz


People also ask

What is Iterable interface in Java?

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).

What implements Iterable in Java?

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.

Where is Iterator interface implemented?

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.

What is the difference between Iterator and iterable interfaces in Java?

Iterator is an interface, which has implementation for iterate over elements. Iterable is an interface which provides Iterator.


1 Answers

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.

like image 123
aioobe Avatar answered Sep 18 '22 19:09

aioobe