List接口簡介
List中的元素是有序的、可以重複並且可以爲null,一般推薦使用ArrayList實現類。
1. 父類
List接口繼承自Collection接口,並新增了操作方法,如下表:
方法 | Collection | List |
---|---|---|
int size() | 存在 | 存在 |
boolean isEmpty() | 存在 | 存在 |
boolean contains(Object o) | 存在 | 存在 |
Iterator iterator() | 存在 | 存在 |
Object[] toArray() | 存在 | 存在 |
T[] toArray(T[] a) | 存在 | 存在 |
boolean add(E e) | 存在 | 存在 |
boolean remove(Object o) | 存在 | 存在 |
boolean containsAll(Collection c) | 存在 | 存在 |
boolean addAll(Collection c) | 存在 | 存在 |
boolean removeAll(Collection c) | 存在 | 存在 |
boolean retainAll(Collection c) | 存在 | 存在 |
void clear() | 存在 | 存在 |
boolean equals(Object o) | 存在 | 存在 |
int hashCode() | 存在 | 存在 |
E get(int index) | 新增 | |
E set(int index, E element) | 新增 | |
void add(int index, E element) | 新增 | |
E remove(int index) | 新增 | |
int indexOf(Object o) | 新增 | |
int lastIndexOf(Object o) | 新增 | |
ListIterator listIterator() | 新增 | |
ListIterator listIterator(int index) | 新增 | |
List subList(int fromIndex, int toIndex) | 新增 |
2. 實現類
List下有ArrayList、Vector、LinkedList實現類,Vector下有Stack子類。
ArrayList
1、ArrayList是基於數組實現,其實內部是個動態數組。
2、ArrayList繼承自AbstractList,實現了List(增刪改查), RandomAccess(隨機訪問), Cloneable(克隆), java.io.Serializable(序列化)接口。
class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable
3、ArrayList的操作方法沒有實現同步,不是線程安全的,同步可以使用Vector、java.util.concurrent.CopyOnWriteArrayList(推薦使用)類。
LinkedList
1、LinkedList基於鏈表實現。
2、LinkedList繼承自AbstractSequentialList,實現了List(增刪改查), Deque(雙向隊列), Cloneable(克隆), java.io.Serializable(序列化)接口。
class LinkedList<E> extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable, java.io.Serializable
3、LinkedList基於鏈表,沒實現隨機訪問接口,訪問時比ArrayList慢;但是頻繁插入或刪除元素時使用LinkedList列表性能會更好。
Vector
Vector繼承的類和實現的接口和ArrayList相同,不同點事Vector類中對於集合元素的操作方法都使用了synchronized關鍵字修飾,提供同步的方法。是線程安全的,但是性能較差,單線程推薦使用ArrayList。
Stack
1、Stack是一個後進先出(last in first out,LIFO)的堆棧。
2、繼承Vector類,並增加了push,pop,peek,empty,search方法。
3. 與其他集合類型比較
List與Array
相同點:同一類型的一組對象;可以使用下標訪問。
不同點:數組可以使用所有類型,List只能使用包裝類型;數組容量固定不變,List長度可變;數組效率比List高。
固定長度時,使用數組,更省空間,更高效;變化長度使用List更好。
List與Set
相同點:繼承自Collection接口,可以保存一組相同類型的數據。
不同點:元素順序不同,List有序,Set無序;List可以有重複值,Set不能重複。