List集合介紹&常用方法
List特點:
1.是有序的集合
2.有索引
3.元素可以重複
List接口中帶索引的方法(特有)
-public void add(int index, E element):將指定的元素,添加到該集合的指定位置上。
-public E get (int index):返回集合中指定位置的元素。
-public E remove(int index):移除列表中指定位置的元素,返回的是被移除的元素。
-public E set(int index, E element):用指定元素替換集合中指定位置的元素,返回值的更新前的元素。
*操作索引的時候,一定要防止索引越界異常
IndexOutOfBoundsException:索引越界異常,集合會報
ArrayIndexOutOfBoundsException:數組索引越界異常
StringIndexOutOfBoundsException:字符串索引越界異常
list遍歷的三種方式:
1.使用普通的for循環
2.使用迭代器
3.使用增強for循環
package test;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class DemoList {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("a");
list.add("b");
list.add("c");
list.add("a");
System.out.println(list);
list.add(1,"e");
String re = list.remove(2);
System.out.println("被移除的元素:"+re);
String re2 = list.set(3,"A");
System.out.println("被替換的元素:"+re2);
for (int i = 0; i < list.size(); i++) {
System.out.print(list.get(i));
}
System.out.println();
for(Iterator<String> i=list.iterator();i.hasNext();){
System.out.print(i.next());
}
System.out.println();
for(String i:list){
System.out.print(i);
}
System.out.println();
}
}