Home > Software engineering >  How to return an iterable in Java?
How to return an iterable in Java?

Time:04-08

I have a class with the following arraylist:

private ArrayList<MyVertex> vertices;

This class also has the following nested class:

public class MyVertex implements Vertex<Integer>{
    private int index;  
    private String name;
    private int degree;
    public MyVertex(int index, String name) {
        this.index=index; 
        this.name=name;
        this.degree=0;
    }
    public String getName() {
        return name;
    }
    @Override
    public Integer getElement() {
        return index;
    }
    @Override
    public String toString() {
        return "v" index ":" name;
    }
}

In this class, I have the following method:

public Iterable<Vertex<Integer>> vertices() {
    return (Iterable<Vertex<Integer>>) new ArrayList<Vertex<Integer>>();
}

My problem is that I have no clue what it means to return an iterable. I thought doing something like

return vertices.iterator();

would work but it didn't. All I know is that the method should run in O (n) time. If anyone could help I would appreciate it. Thank you.

CodePudding user response:

The Iterable interface provides the methods that allow an object to be the target of a "for each" statement.

For example:

class Main {
  public static void main(String[] args) {
    ArrayList<String> list = new ArrayList<String>();
    list.add("Alpha");
    list.add("Bravo");
    list.add("Charlie");

    for (String s : list)
        System.out.println(s);
}

The for loop works because ArrayList<E> implements the Enumerable<E> interface.

That means your method:

public Iterable<Vertex<Integer>> vertices() {
    return (Iterable<Vertex<Integer>>) new ArrayList<Vertex<Integer>>();
}

Can be written as

public Iterable<Vertex<Integer>> vertices() {
    return new ArrayList<Vertex<Integer>>();
}

without the cast. It returns an Iterable.

Further Reading
Class ArrayList
Interface Iterable

CodePudding user response:

ArrayList is an Iterable

Iterable is an interface with one required method: iterator that returns an Iterator.

The ArrayList class already implements Iterable. Indeed, any implementation of the interface List is required to implement Iterable.

  •  Tags:  
  • java
  • Related