首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

java中数组剔除操作注意事项

2012-12-23 
java中数组删除操作注意事项List commonList new ArrayList()commonList.add(...)......?if (commonLi

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);
??? ??? ??? }
??? ??? }

热点排行