List(列表)
List的主要特征是其元素以线性方式存储,集合中允许存放重复对象。List接口主要的实现类包括:
ArrayList – 代表长度可变的数组。允许对元素进行快速的随机访问,但是向ArrayList中插入与删除元素的速度较慢。
LinkedList – 在实现中采用链表数据结构。对顺序访问进行了优化,向List中插入和删除元素的速度较快,随机访问速度则相对较慢。
随机访问是指检索位于特定索引位置的元素。LinkedList单独具有addFirst() addLast() getFirst() getLast() removeFirst() removeLast()方法,这些方法使得LinkedList可以作为堆栈、队列和双向队列来使用。
1.3.1 访问列表的元素
public static void main(String[] args) { List<Integer> list = new ArrayList<Integer>(); list.add(new Integer(3)); list.add(new Integer(4)); list.add(new Integer(3)); list.add(new Integer(2)); for(int i=0;i<list.size();i++){ System.out.println(list.get(i)+" "); } } |
List的get(int index)方法返回集合中由参数指定的索引位置的对象,第一个加入到集合中的对象的索引位置为0。
List的iterator()方法和Set的iterator()方法一样,也能返回Iterator()对象,可以用Iterator来遍历集合中的所有对象。
Iterator<Integer> it = list.iterator(); while(it.hasNext()){ System.out.println(it.next()); } |
1.3.2 为列表排序
List只能对集合中的对象按索引位置排序,如果希望对List中对象按其他特定方式排序,可以借助Comparator接口和Collections类。Collections类是java集合类库中的辅助类,它提供了操纵集合的各种静态方法,其中sort()方法用于对List中的对象进行排序。
Sort(List list):对list中的对象进行自然排序。
Sort(List list,Comparator comparator):对List中的对象进行客户化排序,comparator参数指定排序方式。
List<Integer> list = new ArrayList<Integer>(); list.add(new Integer(3)); list.add(new Integer(4)); list.add(new Integer(2)); list.add(new Integer(3));
Collections.sort(list);
for(int i=0;i<list.size();i++) System.out.println(list.get(i));
|
1.3.3 ListIterator接口
List的listIterator()方法返回一个ListIterator对象,ListIterator接口继承了Iterator接口,此外还提供了专门操纵列表的方法。
|-add()向列表中插入一个元素
|-hasNext() 判断列表中是否还有下一个元素
|-hasPrevious() 判断列表中是否还有上一个元素
|-next()返回列表中的下一个元素
|-preious()返回列表中的上一个元素