我有以下代码:
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
}
}
Run Code Online (Sandbox Code Playgroud)
我突出显示了无效的线路.在这里,我尝试向路线添加新对象.在主文件路由是:
public class RouterMain
{
public static void main(String[] arg) throws IllegalArgumentException
{
List<Route> routes = new ArrayList<Route>();
Router router = new Router(routes);
}
}
Run Code Online (Sandbox Code Playgroud)
任务是在Router类中的可迭代对象中添加一个对象.据我Iterable所知,可以迭代,而不是添加一些东西.那么我应该怎么做,将Router类中的路由转换为a List,添加一个元素然后返回?
Iterable<Router>用于启用迭代Router类中包含的元素.虽然许多集合实现了这个接口,但它不是Collection.它没有这个add方法.它只有一个返回的方法Iterator<Router>.
您应该使用一些Collection(List,Set等)来存储您的路线.那些收藏品有add方法.
public class Router {
private List<Route> routes = new ArrayList<Route>();
public Router(Iterable<Route> routes) {
for (Route route : routes)
this.routes.add(route);
}
}
Run Code Online (Sandbox Code Playgroud)
小智 0
如果您想添加到它,您可以创建一个新列表并将所有当前元素添加到该列表中,然后只需在例如之后添加您想要的对象
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);
}
}
Run Code Online (Sandbox Code Playgroud)