最近在搞一个购物车的功能,里面有一个批量删除的操作,采用的是ExpandableListView以及BaseExpandableListAdapter。视乎跟本篇无关紧要,主要是为了记录一个java基础。迭代器iterator的使用
一、错误代码(主要就是购物车的批量删除)
/**
* 删除选中的
*/
public void delSelect() {
int groupSize;
if (mGropBeens != null) {
groupSize = mGropBeens.size();
} else {
return;
}
for (int i = 0; i < groupSize; i++) {
int childSize = mGropBeens.get(i).getChildBean().size();
for (int j = 0; j < childSize; j++) {
if (mGropBeens.get(i).getChildBean().get(j).isChecked()) {
DataSupport.deleteAll(ShopcartBean.class, "product_id=?", mGropBeens.get(i).getChildBean().get(j).getProduct_id());
mGropBeens.get(i).getChildBean().remove(j);
}
}
}
notifyDataSetChanged();
}
分析一、其实就是一个循环遍历list进行remove的操作,后来我分析了一下,错误的很明显,就是你remove了这个list以后,list的长度就改变了,然后你继续遍历,就会报错。感觉躲不了啊。错误有了,我觉得无法下手,后面既然remove不了,我就先删除本地数据库的方式,然后遍历对data进行赋值。。。躲一下
/**
* 删除选中的
*/
public void delSelect() {
int groupSize;
if (mGropBeens != null) {
groupSize = mGropBeens.size();
} else {
return;
}
for (int i = 0; i < groupSize; i++) {
int childSize = mGropBeens.get(i).getChildBean().size();
for (int j = 0; j < childSize; j++) {
if (mGropBeens.get(i).getChildBean().get(j).isChecked()) {
DataSupport.deleteAll(ShopcartBean.class, "product_id=?", mGropBeens.get(i).getChildBean().get(j).getProduct_id());
// mGropBeens.get(i).getChildBean().remove(j);
}
}
}
//刷新数据源
for (int i = 0; i < mGropBeens.size(); i++) {
mGropBeens.get(i).getChildBean().clear();
List<ShopcartBean> shopcartBeanlists = DataSupport.where("top_category_id=?", mGropBeens.get(i).getGroupId()).find(ShopcartBean.class);
mGropBeens.get(i).setChildBean(shopcartBeanlists);
}
notifyDataSetChanged();
}
分析二、写了这样以后还是感觉很不爽啊。明明我都循环了一遍知道要删除这个对象了,还要等遍历完,仅仅改变它的适配器的data。感觉不爽,随意的百度了下,发现有专门的解决方案,就是迭代器iterator
二、争取的打开方式
/**
* 删除选中的
*/
public void delSelect() {
int groupSize;
if (mGropBeens != null) {
groupSize = mGropBeens.size();
} else {
return;
}
for (int i = 0; i < groupSize; i++) {
Iterator<ShopcartBean> iterator = mGropBeens.get(i).getChildBean().iterator();
while (iterator.hasNext()) {
ShopcartBean shopcartBean = iterator.next();
if (shopcartBean.isChecked()) {
DataSupport.deleteAll(ShopcartBean.class, "product_id=?", shopcartBean.getProduct_id());
iterator.remove();
}
}
}
notifyDataSetChanged();
}
分析三、发现这个玩意感觉还是很惊喜的,同时也感叹自己基础薄弱了。
一般循环for和foreach都需要先知道集合的类型,甚至是集合内元素的类型,即需要访问内部的成员;iterator是一个接口类型,他不关心集合或者数组的类型,而且他还能随时修改和删除集合的元素。他不包含任何有关他所遍历的序列的类型信息,能够将遍历序列的操作与序列底层的 结构分离。
基本使用模式就是:
List<object> arr=xxx;//把你的list赋值过来
Iterator it = arr.iterator();
while(it.hasNext()){
object o =it.next();//当前遍历对象
iterator.remove();//删除或修改等等
}
三、ok,先做记录,后面继续深入。have a nice day.这就是在一个list中删除多个元素的正确解法。