list接口:有下標,存取有序,允許有重復的元素(equals方法),比較是否有重復的元素。
常用接口實現類:ArrayList集合 Linkedlist集合
1 //有序 可重復 有下標值 2 List<String> arr=new ArrayList<String>();//此時多態創建對象,仍為集合 3 arr.add("1"); 4 //向指定的位置上添加元素,原有元素后移 5 arr.add(0,"2"); 6 arr.add(1,"2"); 7 //獲得指定下標上的元素 8 System.out.println(arr.get(0)); 9 //刪除指定位置的元素 10 System.out.println("刪除的元素為"+arr.remove(1)); 11 //刪除指定的元素 返回布爾值 12 System.out.println("刪除的元素為"+arr.remove("1")); 13 //替換指定位置上的元素 14 arr.set(1, "hello"); 15 //3種遍歷方式 迭代器 強for循環 普通for循環 16 for(int i=0;i<arr.size();i++){ 17 System.out.println(arr.get(i)); 18 }
如何在迭代過程中添加元素:最好別再一個集合迭代中添加刪除元素
1 一種替代方案可以是Collection將新創建的元素添加到單獨的元素,然后迭代這些元素: 2 3 Collection<String> list = Arrays.asList(new String[]{"Hello", "World!"}); 4 Collection<String> additionalList = new ArrayList<String>(); 5 6 for (String s : list) { 7 // Found a need to add a new element to iterate over, 8 // so add it to another list that will be iterated later: 9 additionalList.add(s); 10 } 11 12 for (String s : additionalList) { 13 // Iterate over the elements that needs to be iterated over: 14 System.out.println(s); 15 }