集合框架之List

来源:互联网 发布:ubuntu给予文件夹权限 编辑:程序博客网 时间:2024/05/17 08:38

常用方法:
(1)、添加
void add(int Index , E element):在list的指定位置插入元素
void addAll(int index , Collection e):将指定collection中的所有元素插入到列表中的指定位置

(2)、删除
E remove(int Index):删除指定位置的元素,并返回该元素;

(3)、修改
E set(int index , E element):替换指定位置的元素,并返回被替换的元素

(4)、获取
Int indexOf(Object o):返回指定元素第一次出现的索引,如果该list中不含则返回-1;
E get(int Index):返回指定位置的元素;
List sublist(int fromIndex , int toIndex):返回列表指定的fromIndex(包括)和toIndex(不包括)之间的部分视图(list);

注意:对list进行迭代的时候不能对list经常操作(增删改)
可以使用Iterator接口的子接口ListIterator来完成在迭代过程中对list进行操作,list.listIterator()方法返回此列表元素的列表迭代器,此迭代器可以倒序迭代(hasPrevious()方法和previous()),注意在对list作操作时应该对listIterator对象进行操作,

示例:

While(it.hasNext()){           // 注意这里不能用list.add(“demo”)!!!!!!           It.add(“demo”);}

常用的对象
Vector:内部是数组数据结构,是同步的,100%延长数组,增删查询都很慢
ArrayList:内部是数组数据结构,是不同步的,替代Vector,50%延长数组,查询的速度快。
LinkedList:内部是链表数据结构,是不同步的,增删元素速度快。

常见对象详解
1:Vector
枚举

Enumeration en = v.elements();While(en.hasMoreElements()){         System.out.println(en.nextElement());}

注意:枚举和迭代器相同,只是没有remove()方法,推荐使用迭代器

2、 LinkedList

Linkedlist.add(“demo1”);Linkedlist.add(“demo2”);Linkedlist.add(“demo3”);System.out.print(linkedlist);

输出[demo3,demo2,demo1];

当用LinkedList迭代时,元素是倒序输出,Linkedlist 的getFirst()当没有获取到数据时抛出异常NoSuchElementException,但是1.6版本的peekFirst()会返回null,(pollFirst()对应removeFirst())。

参考博客:http://www.cnblogs.com/orlion/p/4817921.html