我有以下代码:
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
}
}
我突出显示了无效的线路.在这里,我尝试向路线添加新对象.在主文件路由是:
public class RouterMain
{
public static void main(String[] arg) throws IllegalArgumentException
{
List<Route> routes = new ArrayList<Route>();
Router router = new Router(routes);
}
}
任务是在Router类的iterable对象中添加一个对象.据我所知,Iterable可以迭代,而不是添加一些东西.那么我该怎么办,将Router类中的路由转换为List,添加一个元素并返回?
解决方法:
如果要添加它,您可以创建一个新列表并将所有当前元素添加到该列表中,然后只需添加您想要的对象,例如
public class Router {
private Iterable<Route> routes;
public Router(Iterable<Route> routes) {
this.routes = routes;
}
public void addRoute(Route route) {
//create new list
ArrayList<Route> myList = new ArrayList<Route>();
//iterate through current objects and add them to new list
Iterator<Route> routeIterator = routes.iterator();
while(routeIterator.hasNext()){
myList.add(routeIterator.next());
}
//add object you would like to the list
myList.add(route);
}
}