[英]IndexOutOfBoundsException when removing ArrayList element
[英]Receiving IndexOutOfBoundsException when removing item from Java ArrayList
我有一个值列表。 取消选中复选框后,我想删除列表项:
ArrayList<SalesRoutes> routeList = new ArrayList<SalesRoutes>();
ArrayList<String> selectedRoutes = new ArrayList<String>();
routeList =getSalesRoute();
for (int i = 0; i < routeList.size(); i++) {
CheckBox ch = new CheckBox(this);
ch.setId(i);
ch.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
if(arg0.isChecked()){
Log.i("add", routeList.get(arg0.getId()).getRouteCode());
selectedRoutes.add(routeList.get(arg0.getId()).getRouteCode());
System.out.println("----add ----" + selectedRoutes);
}else {
selectedRoutes.remove(arg0.getId());
Log.i("remove", routeList.get(arg0.getId()).getRouteCode());
System.out.println("----remove ----" + selectedRoutes);
}
}
});
}
在这里我得到了IndexOutOfBoundsException
因为selectedRoutes被选中了CheckBox值
selectedRoutes
[R0002]
routeList在屏幕上显示路由列表。 它从数据库获取路由。
routeList示例:
Route List
R0001
R0002 // selected this one ID is 1
R0003
从selectedRoutes(1)调用remove。
selectedRoutes.remove(arg0.getId());
这里的selectedRoutes只包含一个记录,这意味着没有索引1。
我该如何删除?
问题在于这段代码:
selectedRoutes.remove(arg0.getId());
Log.i("remove", routeList.get(arg0.getId()).getRouteCode());
System.out.println("----remove ----" + selectedRoutes);
您(通常是错误的)假设是,潜在路线列表中的路线索引与选定路线列表中的路线索引相同。 相反,您将需要在该索引的潜在路由列表中获取该路由的路由代码,然后遍历所选路由列表(实际上只是包含路由代码的字符串),并删除两个索引配对。 代码如下所示:
String routeCode = routeList.get(arg0.getId()).getRouteCode();
index = -1;
for(int i = 0; i < selectedRoutes.size(); i++) {
if(routeCode.equals(selectedRoutes.get(i)) {
index = i;
break;
}
}
if(index > -1)
selectedRoutes.remove(index);
Log.i("remove", routeCode);
System.out.println("----remove ----" + selectedRoutes);
如果将selectedRoutes创建为相同对象ArrayList<SalesRoutes> selectedRoutes
的集合,那会容易得多。 由于两个集合都包含对同一对象的引用,因此您可以通过引用删除该对象:
salectedRoutes.remove(routeList.get(arg0.getId()));
调用ArrayList.remove(int location)将删除数组中该位置的对象。 它不会通过其ID值移除对象。
看来您是在.getRouteCode()返回的索引位置处将对象添加到arraylist中
但是,然后您尝试在.getId()返回的索引位置处删除对象。
两者不同步。
您已经混合使用ArrayList.remove(int index)
和ArrayList.remove(Object o)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.