Java集合类库将集合的接口与实现分离。同样的接口,可以有不同的实现。
Java集合类的基本接口是Collection接口。而Collection接口必须实现Iterator接口。
以下图表示集合框架的接口,java.lang以及java.util两个包里的。红色字体部分是OCJP考纲要求的接口。其他部分可以从左向右看,比如Collection的Subinterfaces有List,Set以及Queue等。
Iterator接口包含三个方法:
Iterable接口仅包含一个方法:
for-each循环可以与任何实现了Iterable接口的对象一起工作。
此接口的方法
public interface Collection<E>{......}
Modifier and Type | Method and Description |
---|---|
boolean |
add(E e)
Ensures that this collection contains the specified element (optional operation).
|
boolean |
addAll(Collection<? extends E> c)
Adds all of the elements in the specified collection to this collection (optional operation).
|
void |
clear()
Removes all of the elements from this collection (optional operation).
|
boolean |
contains(Object o)
Returns true if this collection contains the specified element.
|
boolean |
containsAll(Collection<?> c)
Returns true if this collection contains all of the elements in the specified collection.
|
boolean |
equals(Object o)
Compares the specified object with this collection for equality.
|
int |
hashCode()
Returns the hash code value for this collection.
|
boolean |
isEmpty()
Returns true if this collection contains no elements.
|
Iterator<E> |
iterator()
Returns an iterator over the elements in this collection.
|
boolean |
remove(Object o)
Removes a single instance of the specified element from this collection, if it is present (optional operation).
|
boolean |
removeAll(Collection<?> c)
Removes all of this collection's elements that are also contained in the specified collection (optional operation).
|
boolean |
retainAll(Collection<?> c)
Retains only the elements in this collection that are contained in the specified collection (optional operation).
|
int |
size()
Returns the number of elements in this collection.
|
Object[] |
toArray()
Returns an array containing all of the elements in this collection.
|
<T> T[] |
toArray(T[] a)
Returns an array containing all of the elements in this collection; the runtime type of the returned array is that of the specified array.
|
实现Collection接口的每一个类都要实现以上众多方法,但开发者自己实现很麻烦。所以java提供了AbstractCollection类来编写具体的类。
以下类都实现了Collection接口:
AbstractCollection, AbstractList, AbstractQueue, AbstractSequentialList, AbstractSet, ArrayBlockingQueue, ArrayDeque, ArrayList, AttributeList, BeanContextServicesSupport, BeanContextSupport, ConcurrentLinkedDeque,ConcurrentLinkedQueue, ConcurrentSkipListSet, CopyOnWriteArrayList, CopyOnWriteArraySet, DelayQueue, EnumSet, HashSet, JobStateReasons, LinkedBlockingDeque, LinkedBlockingQueue, LinkedHashSet, LinkedList,LinkedTransferQueue, PriorityBlockingQueue, PriorityQueue, RoleList, RoleUnresolvedList, Stack, SynchronousQueue, TreeSet, Vector
Collection接口有三个常用的子接口,分别是List,Set,Queue。
转自:http://blog.csdn.net/xujinsmile/article/details/8543544