Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add element to iterable in java

Tags:

java

iterable

add

I have the following code:

public class Router {
  private Iterable<Route> routes;

  public Router(Iterable<Route> routes) {
    this.routes = routes;
  }
  public void addRoute(Route route) {
    routes.add(route);\\problem is here
  }
}

I highlighted the line which is not working. Here I try to add a new object to the routes. In main file routes are:

public class RouterMain 
{
    public static void main(String[] arg) throws IllegalArgumentException 
    {
        List<Route> routes = new ArrayList<Route>();
        Router router = new Router(routes);
    }
}

The task is to add an object in iterable object in Router class. As I understood Iterable can iterate, not add something. So what should I do, convert routes in Router class to a List, add an element and go back?

like image 468
ovod Avatar asked Dec 09 '14 15:12

ovod


People also ask

How do you add an element to an iterator?

The add() method of ListIterator interface is used to insert the given element into the specified list. The element is inserted automatically before the next element may return by next() method.

Can we add elements while iterating Java?

You can't modify a Collection while iterating over it using an Iterator , except for Iterator. remove() . This will work except when the list starts iteration empty, in which case there will be no previous element. If that's a problem, you'll have to maintain a flag of some sort to indicate this edge case.

Can we add elements while iterating Arraylist?

ListIterator supports to add and remove elements in the list while we are iterating over it. listIterator. add(Element e) – The element is inserted immediately before the element that would be returned by next() or after the element that would be returned previous() method.


1 Answers

Iterable<Router> is used to enable iterating over the Router elements contained in your class. It is not a Collection, though many collections implement this interface. It doesn't have the add method. It only has a method that returns an Iterator<Router>.

You should use some Collection (List, Set, etc...) to store your routes. Those collections have add method.

public class Router {
  private List<Route> routes = new ArrayList<Route>();

  public Router(Iterable<Route> routes) {
    for (Route route : routes)
      this.routes.add(route);
  }

}
like image 196
Eran Avatar answered Sep 22 '22 19:09

Eran