做编程的一个知识:不要在轮回进程中删除元素自己(至少是我小我私家的原则)。不然将产生不行预料的问题。
而最近,看到一个以前的同学写的一段代码就是在轮回进程中删除元素,我极端烦闷啊。然后厥后抉择给他改掉。然后激发了别的的惨案。
本来的代码是这样的:
public List<A> getUserDebitCard(A cond) {
List<A> list = userService.getCard(cond);
List<A> result = null;
if(list! = null && list.size() > 0){
Collections.sort(list, new Comparator<A>(){
public int compare(A b1, A b2) {
//定时间排序
if(Integer.valueOf(b1.getAddTime()) > Integer.valueOf(b2.getAddTime())){
return -1;
}
return 1;
}
});
A bean = getA(cond);
result = new ArrayList<A>();
if(bean!=null){
for (int i = 0; i < list.size(); i++) {
if(list.get(i).getCardNum().equals(bean.getCardNum())){
list.get(i).setAs(1);
result.add(list.get(i));
list.remove(i);
}else{
list.get(i).setAs(0);
}
}
}
result.addAll(list);
}
return result;
}
看了如上代码,我极端郁闷,然后给改成如下:
public List<A> getUserDebitCard(A cond) {
List<A> list=userService.getCard(cond);
List<A> result=null;
if(list!=null && list.size()>0){
Collections.sort(list, new Comparator<A>(){
public int compare(A b1, A b2) {
//定时间排序
if(Integer.valueOf(b1.getAddTime()) > Integer.valueOf(b2.getAddTime())){
return -1;
}
return 1;
}
});
A bean = getA(cond);
result=new ArrayList<>();
if(bean != null){
// 将上次的卡安排在第一位
Integer lastAIndex = 0;
Integer listSize = list.size();
if(listSize > 0) {
for (int i = 0; i < listSize; i++) {
if (list.get(i).getCardNum().equals(bean.getCardNum())) {
list.get(i).setAs(1);
result.add(list.get(i)); //将排在首位的元素先添加好,并记录下index
lastAIndex = i;
// list.remove(i); //轮回进程中删除元素是危险的
} else {
list.get(i).setAs(0);
}
}
list.remove(lastAIndex);
}
}
result.addAll(list); //在轮回外删除元素,觉得万事大吉,功效悲剧了,这里居然添加了两个元素进来
}
return result;
}
这下失事了,原本只有一个元素的result,此刻酿成了两个了,这是为什么呢?妈蛋,我显着已经remove掉了啊。
也想过百度一下,可是木有搞定啊。然后,拿出看家绝招,断点调试,进入list.remove(Integer) 要领。其源码如下:
/**
* Removes the first occurrence of the specified element from this list,
* if it is present. If the list does not contain the element, it is
* unchanged. More formally, removes the element with the lowest index
* <tt>i</tt> such that
* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>
* (if such an element exists). Returns <tt>true</tt> if this list
* contained the specified element (or equivalently, if this list
* changed as a result of the call).
*
* @param o element to be removed from this list, if present
* @return <tt>true</tt> if this list contained the specified element
*/
public boolean remove(Object o) {
if (o == null) {
for (int index = 0; index < size; index++)
if (elementData[index] == null) {
fastRemove(index);
return true;
}
} else {
for (int index = 0; index < size; index++)
if (o.equals(elementData[index])) {
fastRemove(index);
return true;
}
}
return false;
}
本来,由于我利用Integer作为删除元素的条件,这里把Integer看成一个元素去较量了,而并不是平时我们觉得的自动拆装箱变为int了。 而进入这个要领的意思,是要找到和元素内容相等的元素,然后删除它。而我给的是一个索引,自然就不相等了,没有删除也是自然了,因为就会看到反复的元素出来了。