List集合为列表类型,主要特征是以线性方式存储对象。List包括List接口以及List接口的所有实现类,List接口实现了Collection接口,List接口的常用实现类包括ArrayList类和LinkedList类。
1.1 List的用法
常用方法:
- add(int index, Object obj):向集合的指定索引位置添加对象,其他对象的索引位置相对后移一位,索引位置从0开始。
- addAll(int index, Collection coll):向集合的指定索引位置添加指定集合中的所有对象。
- remove(int index):清除集合中指定索引位置的对象。
- set(int index, Object obj):将集合中指定索引位置的对象修改为指定的对象。
- get(int index):获取集合中指定索引位置的对象。
- indexOf(Object obj):获取集合中指定对象的索引,当存在多个时,返回第一个的索引位置,当不存在时,返回-1。
- lastIndexOf(Object obj):获取集合中指定对象的索引,当存在多个时,返回最后一个的索引位置,当不存在时,返回-1。
- listIterator():获取一个包含所有对象的ListIterator型实例。
- listIterator(int index):获取一个包含从指定索引位置到最后的ListIterator型实例。
- subList(int fromIndex, int toIndex):截取从起始索引位置fromIndex(包含)到终止索引位置toIndex(不包含)的对象,重新生成一个List集合并返回。
1.2 ArrayList类
ArrayList类实现了List接口,采用数组结构保存对象。优点是便于对集合进行快速的随机访问,缺点是向指定索引位置插入对象和删除对象的速度较慢。
【例】编写一个模仿经常需要随机访问集合中对象的例子。
public static void main(String[] args){
String a = "A", b = "B", c = "C", d = "D", e = "E";
List<String> list = new ArrayList<String>();
list.add(a);
list.add(b);
list.add(c);
list.add(d);
list.add(e);
System.out.println(list.get((int)(Math.random() * 5)));
}
在编写该例子时,用到了java.lang.Math类的random()方法,通过该方法可以得到一个小于1的的double型随机数,将该随机数乘以5后再强制转换成整数,可得到一个0~4的整数。
1.3 LinkedList
LinkedList类实现了List接口,采用链表结构保存对象。优点是便于向集合中插入和删除对象,缺点是随机访问对象速度较慢。
LinkedList类在List接口的基础之上增加的常用方法:
- addFirst(Object obj):将指定对象插入到列表的开头。
- addLast(Object obj):将指定对象插入到列表的截尾。
- getFirst():获得列表开头的对象。
- getLast():获得列表结尾的对象。
- removeFirst():移除列表开头的对象。
- removeLast() :移除列表结尾的对象。
【例】使用LinkedList类。
public static void main(String[] args){
String a = "A", b = "B", c = "C", test = "test";
LinkedList<String> list = new LinedLis<String>();
list.add(a);
list.add(b);
list.add(c);
System.out.println(list.getFirst());
list.addFirst(test);
System.out.println(list.getFirst());
list.removeFirst();
System.out.println(list.getFirst());
}