我有这五种方法来迭代 ArrayList,这些是
public static void main(String[] argv) {
// create list
List<String> aList = new ArrayList<String>();
// add 4 different values to list
aList.add("eBay");
aList.add("Paypal");
aList.add("Google");
aList.add("Yahoo");
// iterate via "for loop"
System.out.println("==> For Loop Example.");
for (int i = 0; i < aList.size(); i++) {
System.out.println(aList.get(i));
}
// iterate via "New way to loop"
System.out.println("\n==> Advance For Loop Example..");
for (String temp : aList) {
System.out.println(temp);
}
// iterate via "iterator loop"
System.out.println("\n==> Iterator Example...");
Iterator<String> aIterator = aList.iterator();
while (aIterator.hasNext()) {
System.out.println(aIterator.next());
}
// iterate via "while loop"
System.out.println("\n==> While Loop Example....");
int i = 0;
while (i < aList.size()) {
System.out.println(aList.get(i));
i++;
}
// collection stream() util: Returns a sequential Stream with this collection as its source
System.out.println("\n==> collection stream() util....");
aList.forEach((temp) -> {
System.out.println(temp);
});
}
我的问题是通过这些方式进行迭代是相同的还是有什么区别?如果是的话,那么这是最好的方法,我的要求是根据某些条件从数组列表中删除一个元素。
最佳答案
my requirement is removing a element from an arraylist based on some condition
如果您必须从 ArrayList
中删除一个元素在迭代它时,使用显式迭代器是基本方式(您的第三个选项)。使用aIterator.remove()
删除当前元素。
增强的 for 循环和 forEach
不允许删除元素,因为您没有当前元素的索引,即使有,在增强的 for 循环中删除元素也会抛出 ConcurrentModificationException。
常规的 for 循环和 while 循环还允许您删除元素,因为您拥有当前元素的索引,但您应该记住在删除元素后递减索引,因为从 ArrayList
中删除元素将该元素之后的所有元素向左移动。
关于java - 迭代数组列表的最佳方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35061582/