List接口的介紹
- java.util.List接口繼承自Collection接口,是單列集合的一個重要分支,習慣性地會將實現了List接口的對象稱為List集合。
- 在List集合中允許出現重復的元素,所有的元素是以一種線性方式進行存儲的,在程序中可以通過索引來訪可集合中的指定元素。
- 另外,List集合還有一個特點就是元素有序,即元素的存入順序和取出順序一致。
List接口的特點
- 它是一個元素存取有序的集合。例如,存元素的順序是11、22、33。那么集合中,元素的存儲就是按照11、22、33的順序完成的。
- 它是一個帶有索引的集合,通過索引就可以精確的操作集合中的元素(與數組的索引是一個道理)。
- 集合中可以有重復的元素,通過元素的 equals方法,來比較是否為重復的元素。
List接口中帶索引的(特有)方法
// 1、將指定的元素,添加到該集合中的指定位置上。
public void add(int index, E element)
// 2、返回集合中指定位置的元素。
public E get(int index)
// 3、移除列表中指定位置的元素,返回的是被移除的元素。
public E remove(int index)
// 4、用指定元素替換集合中指定位置的元素,返回值的更新前的元素。
public E set(int index, E element)
add()方法
說明:
hasNext()方法,獲取迭代器是否含有下一個元素(含有就返回true)
next()方法,獲取迭代器下一個元素
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class DemoListAdd {
public static void main(String[] args) {
// 創建集合對象
List<String> arrayList = new ArrayList<>();
// 往集合的指定位置上添加給定的元素
arrayList.add(0, "Index 0 元素");
arrayList.add(1, "Index 1 元素");
arrayList.add(2, "Index 2 元素");
// 遍歷集合,查看結果
// 獲取迭代器對象
Iterator<String> ite = arrayList.iterator();
// 輸出
while (ite.hasNext()) {
System.out.println(
ite.next()
);
}
}
}
輸出結果:
Index 0 元素
Index 1 元素
Index 2 元素
get()方法
import java.util.ArrayList;
import java.util.List;
public class DemoListGet {
public static void main(String[] args) {
// 創建集合對象
List<String> arrayList = new ArrayList<>();
// 往集合的指定位置上添加給定的元素
arrayList.add(0, "Index 0 元素");
arrayList.add(1, "Index 1 元素");
arrayList.add(2, "Index 2 元素");
// 獲取指定位置中集合的元素
String index0 = arrayList.get(0);
String index1 = arrayList.get(1);
String index2 = arrayList.get(2);
// 輸出
System.out.println("索引0處的元素:" + index0);
System.out.println("索引1處的元素:" + index1);
System.out.println("索引2處的元素:" + index2);
}
}
輸出結果:
索引0處的元素:Index 0 元素
索引1處的元素:Index 1 元素
索引2處的元素:Index 2 元素
remove()方法
public class DemoListRemove {
public static void main(String[] args) {
// 創建集合對象
List<String> arrayList = new ArrayList<>();
// 往集合的指定位置上添加給定的元素
arrayList.add(0, "元素0");
arrayList.add(1, "元素1");
arrayList.add(2, "元素2");
// 查看集合
System.out.println("移除元素前:" + arrayList);
// 刪除集合中的部分元素
arrayList.remove(1);
System.out.println("移除元素1后:" + arrayList);
}
}
輸出結果:
移除元素前:[元素0, 元素1, 元素2]
移除元素1后:[元素0, 元素2]
注意:移除一個元素以后,在被移除元素的后面的每個元素索引減1
set()方法
import java.util.ArrayList;
import java.util.List;
public class DemoListSet {
public static void main(String[] args) {
// 創建集合對象
List<String> arrayList = new ArrayList<>();
// 往集合的指定位置上添加給定的元素
arrayList.add(0, "原始元素0");
arrayList.add(1, "原始元素1");
arrayList.add(2, "原始元素2");
// 查看集合
System.out.println("集合被替換元素前:" + arrayList);
// set方法替換指定位置的元素
arrayList.set(0, "替換元素0");
System.out.println("集合被替換元素后:" + arrayList);
}
}
輸出結果:
集合被替換元素前:[原始元素0, 原始元素1, 原始元素2]
集合被替換元素后:[替換元素0, 原始元素1, 原始元素2]