JAVA集合框架之Collection
JAVA集合框架
前言
想研究框架源码,也不知道从那个框架开始,网上有篇博客说
JAVA集合框架->IOStream->struts->《how tomcat work》
不管了 就按他说的来吧
Collection
Collection是所有集合类的总接口,它在java.util包下
我们看到,常见的List Queue Set都是接口,它们继承了Collection接口
而Collection本身又继承了Iterable接口,这就使Collection一定是可迭代的,所以实现了Collection接口的具体类也必然要实现Iterable接口的方法
Collection接口都抽象出了那些通用方法?
那么,List Queue Set 一类的子接口都有那些共同“行为”可以提取到父接口呢?
从名字可以很容易的判断这些方法的含义
如果面试官问起了 我们就从增删改查4个方面来回忆
增:add , addAll
删:remove removeAll removeIf
改:
查:iterator contains containsAll
再来几个加分项:retainAll(取交集) stream(jdk8新特性 用于支持map()等函数编程)
这些方法看似简单,其实来看一下源码,这些抽象函数都定义了许多规范,希望继承Collection接口的时候遵守
如add(E e)方法
/**
* Ensures that this collection contains the specified element (optional
* operation). Returns <tt>true</tt> if this collection changed as a
* result of the call. (Returns <tt>false</tt> if this collection does
* not permit duplicates and already contains the specified element.)<p>
*
* 不同实现类对于e的限制不同,建议写文档中
* Collections that support this operation may place limitations on what
* elements may be added to this collection. In particular, some
* collections will refuse to add <tt>null</tt> elements, and others will
* impose restrictions on the type of elements that may be added.
* Collection classes should clearly specify in their documentation any
* restrictions on what elements may be added.<p>
* 如果有特殊的原因(不是因为对象已存在于集合中)不同意添加接收到的e,应抛出异常而不是返回false
* If a collection refuses to add a particular element for any reason
* other than that it already contains the element, it <i>must</i> throw
* an exception (rather than returning <tt>false</tt>). This preserves
* the invariant that a collection always contains the specified element
* after this call returns.
*
* @param e element whose presence in this collection is to be ensured
* @return <tt>true</tt> if this collection changed as a result of the
* call
* 在什么情况下应该抛出什么异常
* @throws UnsupportedOperationException if the <tt>add</tt> operation
* is not supported by this collection
* @throws ClassCastException if the class of the specified element
* prevents it from being added to this collection
* @throws NullPointerException if the specified element is null and this
* collection does not permit null elements
* @throws IllegalArgumentException if some property of the element
* prevents it from being added to this collection
* @throws IllegalStateException if the element cannot be added at this
* time due to insertion restrictions
*/
optional operation的含义:
有些实现类可以不支持某些方法,比如一个不可更改的集合,不想支持add方法,则可以在overrride时直接抛出UnsupportedOperationException 异常
toArray() 和 toArray(T[])
前者返回一个Object[]
后者通过传递一个具体类型的数组,通过反射,返回一个具体类型的数组:
String str[] = strList.toArray(new String[0]);
下一篇: Java基础笔记-3