Java中ArrayList和CopyOnWriteArrayList之间的区别
以下是Java中ArrayList和CopyOnWriteArrayList类之间的显着区别。
示例
import java.util.Iterator; import java.util.concurrent.CopyOnWriteArrayList; public class Tester { public static void main(String args[]) { //创建一个数组列表 CopyOnWriteArrayList<String> al = new CopyOnWriteArrayList(); System.out.println("Initial size of al: " + al.size()); //将元素添加到数组列表 al.add("C"); al.add("A"); al.add("E"); al.add("B"); al.add("D"); al.add("F"); al.add(1, "A2"); System.out.println("Size of al after additions: " + al.size()); //显示数组列表 System.out.println("Contents of al: " + al); //从数组列表中删除元素 al.remove("F"); al.remove(2); System.out.println("Size of al after deletions: " + al.size()); System.out.println("Contents of al: " + al); try{ Iterator<String> iterator = al.iterator(); while(iterator.hasNext()) { iterator.remove(); } }catch(UnsupportedOperationException e) { System.out.println("不支持的方法:"); } System.out.println("Size of al: " + al.size()); } }
这将产生以下结果-
输出结果
Initial size of al: 0 Size of al after additions: 7 Contents of al: [C, A2, A, E, B, D, F] Size of al after deletions: 5 Contents of al: [C, A2, E, B, D] 不支持的方法: Size of al: 5