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?
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.
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.
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.
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);
}
}
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