循环遍历和数组列表,并删除指定索引处的元素 [英] Looping through and arraylist and removing elements at specified index

查看:119
本文介绍了循环遍历和数组列表,并删除指定索引处的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试一个练习,我将添加1000个元素到一个数组列表,然后再次从列表中删除(通过指定索引)。这背后的想法是比较LinkedList的性能和ArrayList。

  int totalObjects = 0; 
for(int i = 0; i <1000; i ++)
{
totalObjects + = 1;
al.add(Object+ totalObjects);

}
System.out.println(Arraylist size is+ al.size());

如果我做以下只有一半的元素被删除...为什么? p>

  for(int index = 0; index< al.size(); index ++)
{

al.remove(index);

}
System.out.println(删除后的Arraylist大小为+ al.size());

kind regards
Arian

解决方案

这是因为您正在通过删除来更改索引。如果你删除元素0,元素1现在变成元素0.现在当你下一次删除1,这是以前是元素2和什么是元素1仍然存在于索引0。



要避免这种情况最简单的方法是从头到尾循环。



或者,你可以只删除索引0,直到ArrayList为空。 / p>

I was trying an exercise where I would add 1000 elements to an arraylist and then remove them systematically from the list again(by specifying the index). The idea behind this is to compare the performance of the LinkedList to the ArrayList.

int totalObjects = 0;
    for(int i = 0; i < 1000; i++)
    {
        totalObjects += 1;
        al.add("Object " + totalObjects);

    }
     System.out.println("The Arraylist size is " + al.size());

If i do the following only half of the elements gets removed...why is that?

for(int index = 0; index < al.size(); index++)
    {

        al.remove(index);

    }
    System.out.println("The Arraylist size after removal is " + al.size());

kind regards Arian

解决方案

This happens because you are altering the indexes by removing. If you remove element 0, element 1 now becomes element 0. Now when you next remove 1, that is what used to be element 2 and what was element 1 still exists at index 0.

The easiest way to avoid this is to loop backwards from end to beginning.

alternatively, you could just keep removing index 0 until the ArrayList is empty.

这篇关于循环遍历和数组列表,并删除指定索引处的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆