java中数组删除操作注意事项
List commonList = new ArrayList();
commonList.add(...);
......
?
if (commonList.size() > 3)//如果数组个数大于3个,则删掉后面的,只剩余前三个
??? ??? {
??? ??? ??? for (int i = 3; i <commonList.size() ; i++)
??? ??? ??? {
??? ??? ??? ??? commonList.remove(i);
??? ??? ??? }
??? ??? }
上面写法不能正确执行达到以上需求,因为比如 i=3时,数组将位置为3的元素删除后,数组中的后面元素会依次前移,此时i=4,继续删除位置4的元素,而此时位置3上还是存在元素的,这就导致最后数组中剩余的元素一定大于3。
?
正确实现方法如下:
?
if (commonList.size() > 3)//如果数组个数大于3个,则删掉后面的,只剩余前三个
??? ??? {
??? ??? ??? for (int i = commonList.size() - 1; i >= 3; i--)
??? ??? ??? {
??? ??? ??? ??? commonList.remove(i);
??? ??? ??? }
??? ??? }