前几天做项目时遇到集合遍历删除的问题,由于是初学者,很多东西都没经验,网上多方查询后终于搞定,特此记住。
package testRemove;
import java.util.ArrayList;
import java.util.Iterator;
public class TestRemoveClear
{
public static void main(String[] args)
{
deleteByFor(generateList());//[one]
deleteByFor2(generateList());//[one]
// deleteByNewFor(generateList());
deleteByIterator(generateList());//[one]
}
//方法一:使用普通for循环
public static ArrayList<String> deleteByFor(ArrayList<String> list)
{
for (int i = 0; i < list.size(); i++)
{
if (list.get(i).equals("two"))
{
list.remove(i);
//增加此句,每移除一个元素以后再把i移回来;如果不加此句则输出[one, two, two]
i -= 1;
}
}
System.out.println(list);
return list;
}
//方法二:使用普通for倒序循环
public static ArrayList<String> deleteByFor2(ArrayList<String> list)
{
for (int i = list.size() - 1; i >= 0; i--)
{
if ("two".equals(list.get(i)))
{
list.remove(i);
}
}
System.out.println(list);
return list;
}
//方法三:使用增强for循环 会报错
public static ArrayList<String> deleteByNewFor(ArrayList<String> list)
{
for (String s : list)
{
if (s.equals("two"))
{
list.remove(s);
}
}
System.out.println(list);
return list;
}
//方法四:使用迭代器
public static ArrayList<String> deleteByIterator(ArrayList<String> list)
{
//此处迭代器需使用泛型 如果不使用则需强转String s = (String)iterator.next();
Iterator<String> iterator = list.iterator();
while (iterator.hasNext())
{
String s = iterator.next();
if ("two".equals(s))
{
iterator.remove();
}
}
System.out.println(list);
return list;
}
public static ArrayList<String> generateList()
{
ArrayList<String> list = new ArrayList<String>();
list.add("one");
list.add("two");
list.add("two");
list.add("two");
list.add("two");
return list;
}
}