Collection接口的 子接口 List接口
List接口中的常用的方法:(除了Collection中的方法之外的List中的方法)
-
void add(int index, Object ele) 在index的位置插入ele元素
-
Boolean addAll(int index, Collection ele) 在index的位置插入集合ele
-
Object get(int index) 获取指定位置上的元素
-
int indexOf(Object obj) 返回在当前集合中obj首次出现的位置
-
int lastIndexOf(Object obj) 返回在当前集合中obj末次出现的位置-
-
Object remove(int index) 移除指定位置上的元素,并返回此元素
-
Object set(int index,Object obj) 设置指定位置上的元素为obj(类似于替换)
-
List subList(int fromIndex,int toIndex) 返回该集合从fromIndex到toIndex位置上的子集合(左闭右开)
常用方法:
-
增
add(Object o) -
删
1.remove(int index)
2.remove(Object o) -
改
set(int index,Object obj) -
查
get(int index) -
插入
add(int index, Object ele) -
长度
size() -
遍历
1.Iterator迭代器
2.foreach
代码举例:
import java.util.ArrayList;
public class ListTest {
public static void main(String[] args) {
ArrayList arrayList = new ArrayList();
arrayList.add(123);
arrayList.add("你好");
arrayList.add(456);
System.out.println(arrayList+"\n");
arrayList.add(1, 456);
System.out.println("指定位置插入456后:"+arrayList+"\n");
System.out.println("获取index=0的位置上的元素:"+arrayList.get(0)+"\n");
System.out.println("456首次出现的索引:"+arrayList.indexOf(456)+"\n");
System.out.println("456最后一次出现的索引:"+arrayList.lastIndexOf(456)+"\n");
arrayList.remove(3);
System.out.println("移除index=3的元素后的集合"+arrayList+"\n");
arrayList.set(0, "hello,world");
System.out.println("将index=0的元素设置成hello,world后的集合"+arrayList+"\n");
System.out.println("返回集合索引值为[1,3)上的内容:"+arrayList.subList(1, 3));
}
}