源码版本:JDK 1.7。

集合 Collection,根据已知的内容可以知道有List、Set、Map(严格说,Map不属于Collection)等大类。

先查看 Collection,

public interface Collection<E> extends Iterable<E>

JDK说明如下:

/**
* The root interface in the <i>collection hierarchy</i>. A collection
* represents a group of objects, known as its <i>elements</i>. Some
* collections allow duplicate elements and others do not. Some are ordered
* and others unordered. The JDK does not provide any <i>direct</i>
* implementations of this interface: it provides implementations of more
* specific subinterfaces like <tt>Set</tt> and <tt>List</tt>. This interface
* is typically used to pass collections around and manipulate them where
* maximum generality is desired.
*
* <p><i>Bags</i> or <i>multisets</i> (unordered collections that may contain
* duplicate elements) should implement this interface directly.
*
* <p>All general-purpose <tt>Collection</tt> implementation classes (which
* typically implement <tt>Collection</tt> indirectly through one of its
* subinterfaces) should provide two "standard" constructors: a void (no
* arguments) constructor, which creates an empty collection, and a
* constructor with a single argument of type <tt>Collection</tt>, which
* creates a new collection with the same elements as its argument. In
* effect, the latter constructor allows the user to copy any collection,
* producing an equivalent collection of the desired implementation type.
* There is no way to enforce this convention (as interfaces cannot contain
* constructors) but all of the general-purpose <tt>Collection</tt>
* implementations in the Java platform libraries comply.
*
* <p>The "destructive" methods contained in this interface, that is, the
* methods that modify the collection on which they operate, are specified to
* throw <tt>UnsupportedOperationException</tt> if this collection does not
* support the operation. If this is the case, these methods may, but are not
* required to, throw an <tt>UnsupportedOperationException</tt> if the
* invocation would have no effect on the collection. For example, invoking
* the {@link #addAll(Collection)} method on an unmodifiable collection may,
* but is not required to, throw the exception if the collection to be added
* is empty.
*
* <p><a name="optional-restrictions"/>
* Some collection implementations have restrictions on the elements that
* they may contain. For example, some implementations prohibit null elements,
* and some have restrictions on the types of their elements. Attempting to
* add an ineligible element throws an unchecked exception, typically
* <tt>NullPointerException</tt> or <tt>ClassCastException</tt>. Attempting
* to query the presence of an ineligible element may throw an exception,
* or it may simply return false; some implementations will exhibit the former
* behavior and some will exhibit the latter. More generally, attempting an
* operation on an ineligible element whose completion would not result in
* the insertion of an ineligible element into the collection may throw an
* exception or it may succeed, at the option of the implementation.
* Such exceptions are marked as "optional" in the specification for this
* interface.
*
* <p>It is up to each collection to determine its own synchronization
* policy. In the absence of a stronger guarantee by the
* implementation, undefined behavior may result from the invocation
* of any method on a collection that is being mutated by another
* thread; this includes direct invocations, passing the collection to
* a method that might perform invocations, and using an existing
* iterator to examine the collection.
*
* <p>Many methods in Collections Framework interfaces are defined in
* terms of the {@link Object#equals(Object) equals} method. For example,
* the specification for the {@link #contains(Object) contains(Object o)}
* method says: "returns <tt>true</tt> if and only if this collection
* contains at least one element <tt>e</tt> such that
* <tt>(o==null ? e==null : o.equals(e))</tt>." This specification should
* <i>not</i> be construed to imply that invoking <tt>Collection.contains</tt>
* with a non-null argument <tt>o</tt> will cause <tt>o.equals(e)</tt> to be
* invoked for any element <tt>e</tt>. Implementations are free to implement
* optimizations whereby the <tt>equals</tt> invocation is avoided, for
* example, by first comparing the hash codes of the two elements. (The
* {@link Object#hashCode()} specification guarantees that two objects with
* unequal hash codes cannot be equal.) More generally, implementations of
* the various Collections Framework interfaces are free to take advantage of
* the specified behavior of underlying {@link Object} methods wherever the
* implementor deems it appropriate.
*
* <p>This interface is a member of the
* <a href="{@docRoot}/../technotes/guides/collections/index.html">
* Java Collections Framework</a>.
*
* @param <E> the type of elements in this collection
*
* @author Josh Bloch
* @author Neal Gafter
* @see Set
* @see List
* @see Map
* @see SortedSet
* @see SortedMap
* @see HashSet
* @see TreeSet
* @see ArrayList
* @see LinkedList
* @see Vector
* @see Collections
* @see Arrays
* @see AbstractCollection
* @since 1.2
*/

大意是:

Collection接口是集合框架的根接口。JDK没有为该接口提供任何直接实现,而是提供了更细化的子接口的实现,如Set、List。

所有通用目的的实现类应该提供两个标准构造方法:一个空参数的构造器、一个单参数且参数类型为Collection的构造器。没有强制措施,纯属自觉,JDK很自觉。

每个实现类的同步策略由自己决定。

集合框架接口的很多方法都是基于equals方法,例如contains(obj)。

不过,先不急于深入Collection接口,先看看其继承的Iterable接口,该接口只有一个方法:

public interface Iterable<T> {
Iterator<T> iterator();
}

继续展开 Iterator,还是一个接口:

public interface Iterator<E> {
boolean hasNext();
E next();
void remove();
}

如果使用过该接口,应该明白前两个方法的意义,一个用于判断是否还有下一个元素,另一个用于获取下一个元素同时移动游标。最后一个方法其实是删除当前指向的元素,属于可选的待实现接口方法。

事实上,该接口,Iterator取代了原有的Enumeration接口,对比一下就明白了:

public interface Enumeration<E> {
boolean hasMoreElements();
E nextElement();
}

Iterator 和 Enumeration 如出一辙,只不过 Iterator 更简洁,且多了一个操作。

再返回来看看 Iterable 接口,其唯一的方法是 iterator(),要求返回一个 Iterator对象;所以 Collection 接口的实现们必然实现该方法,来测试一下:

@Test
@SuppressWarnings({ "rawtypes", "unchecked" })
public void testIterator() {
Collection collection = null;
collection = new ArrayList();
collection.add(1);
collection.add(2);
collection.add(3); Iterator iterator = collection.iterator(); // Iterator
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}

OK,现在来看看Collection本身的接口:

public interface Collection<E> extends Iterable<E> {
// Query Operations - 查询操作
int size();
boolean isEmpty();
boolean contains(Object o);
Iterator<E> iterator();
Object[] toArray();
<T> T[] toArray(T[] a); // Modification Operations - 修改操作
boolean add(E e);
boolean remove(Object o); // Bulk Operations - 批量操作
boolean containsAll(Collection<?> c);
boolean addAll(Collection<? extends E> c);
boolean removeAll(Collection<?> c);
boolean retainAll(Collection<?> c);
void clear(); // Comparison and hashing - 对比和哈希
boolean equals(Object o);
int hashCode();
}

不明白为什么还有 iterator() 方法,冗余了吧。

上面的方法,对我来说最需要了解的就是 toArray() 和 toArray(T[] a) :前者就是字面意思,将集合转成数组;后者虽然也是将集合转成数字,但是,会考虑集合的size和给定数组的length,如果给定数组能容纳集合的元素,则直接返回指定的数组(填充集合元素),否则,返回一个新创建的数组! -- 就是说,可能会省略分配内存这一步骤。

来个示例:

@Test
public void testToArray() {
// 定义集合
Collection<String> collection = new ArrayList<>();
for (int i = 0; i != 5; ++i) {
collection.add(new String(new char[] { (char) ('a' + i) }));
collection.add(null);
}
System.out.println(collection); // // 定义目标数组
String[] t1 = new String[9];
Arrays.fill(t1, "xxx");
String[] t2 = new String[10];
Arrays.fill(t2, "xxx");
String[] t3 = new String[11];
Arrays.fill(t3, "xxx");
// 转换
String[] r1 = collection.toArray(t1);
String[] r2 = collection.toArray(t2);
String[] r3 = collection.toArray(t3); // 看看返回的数组是否原有数组
System.out.println(r1 == t1); // false
System.out.println(r2 == t2); // true
System.out.println(r3 == t3); // true System.out.println(Arrays.toString(r1));
System.out.println(Arrays.toString(r2));
System.out.println(Arrays.toString(r3)); // 注意,原数组如果仍有空余空间,全部null
}

>>>>>>>>>>>>>>>>>>>>>>>>>未完待续>>>>>>>>>>>>>>>>>>>>>>>>>

JDK源码阅读之Collection的更多相关文章

  1. JDK源码阅读(三) Collection<T>接口,Iterable<T>接口

    package java.util; public interface Collection<E> extends Iterable<E> { //返回该集合中元素的数量 in ...

  2. JDK源码阅读(三):ArraryList源码解析

    今天来看一下ArrayList的源码 目录 介绍 继承结构 属性 构造方法 add方法 remove方法 修改方法 获取元素 size()方法 isEmpty方法 clear方法 循环数组 1.介绍 ...

  3. JDK源码阅读(一):Object源码分析

    最近经过某大佬的建议准备阅读一下JDK的源码来提升一下自己 所以开始写JDK源码分析的文章 阅读JDK版本为1.8 目录 Object结构图 构造器 equals 方法 getClass 方法 has ...

  4. 利用IDEA搭建JDK源码阅读环境

    利用IDEA搭建JDK源码阅读环境 首先新建一个java基础项目 基础目录 source 源码 test 测试源码和入口 准备JDK源码 下图框起来的路径就是jdk的储存位置 打开jdk目录,找到sr ...

  5. JDK源码阅读-FileOutputStream

    本文转载自JDK源码阅读-FileOutputStream 导语 FileOutputStream用户打开文件并获取输出流. 打开文件 public FileOutputStream(File fil ...

  6. JDK源码阅读-FileInputStream

    本文转载自JDK源码阅读-FileInputStream 导语 FileIntputStream用于打开一个文件并获取输入流. 打开文件 我们来看看FileIntputStream打开文件时,做了什么 ...

  7. JDK源码阅读-ByteBuffer

    本文转载自JDK源码阅读-ByteBuffer 导语 Buffer是Java NIO中对于缓冲区的封装.在Java BIO中,所有的读写API,都是直接使用byte数组作为缓冲区的,简单直接.但是在J ...

  8. JDK源码阅读-RandomAccessFile

    本文转载自JDK源码阅读-RandomAccessFile 导语 FileInputStream只能用于读取文件,FileOutputStream只能用于写入文件,而对于同时读取文件,并且需要随意移动 ...

  9. JDK源码阅读-FileDescriptor

    本文转载自JDK源码阅读-FileDescriptor 导语 操作系统使用文件描述符来指代一个打开的文件,对文件的读写操作,都需要文件描述符作为参数.Java虽然在设计上使用了抽象程度更高的流来作为文 ...

随机推荐

  1. java集群优化——ORM框架查询优化原理

    众所周知,当下的流行的企业级架构中,ORM一直是最基础的部分,在架构设计的底层.对逻辑层提供面向对象的操作支持,而事实总是和我们预想的有所偏差,ORM在提供了较好的操作体验时,也流失了一部分原生SQL ...

  2. 进程process与线程thread

    进程:process是一个外理过程,即然是外理过程,那么它就有生命周期,从进程的启动,运行,直到运行结束,进程终止.进程是程序的执行实例,即运行中的程序,同时也是程序的一个副本,程序是放置于磁盘的,而 ...

  3. mysql--Ubuntu下设置MySQL字符集为utf8

    1.mysql配置文件地址/etc/mysql/my.cnf 2.在[mysqld]在下方添加以下代码[mysqld]init_connect='SET collation_connection = ...

  4. linux命令(43):awk的使用技巧

    AWK是一种处理文本文件的语言,是一个强大的文本分析工具. 之所以叫AWK是因为其取了三位创始人 Alfred Aho,Peter Weinberger, 和 Brian Kernighan 的Fam ...

  5. HA&Federation【转】

    转自:http://blog.csdn.net/tutucute0000/article/details/39756123 从nameNode1.namenode2克隆出namenode3.namen ...

  6. 【嵌入式】bootloader,linux,filesystem的烧写

    平台: 深圳市优龙科技有限公司的FS2410(基于ARM9) 准备: 1.用串口(UART1,J8)线与PC机相连,这个是用来传输数据和显示信息的 2.连接USB数据下载线(usb device),注 ...

  7. 获取控制台窗口句柄GetConsoleWindow

    在创建direct 3D对象时需要一个窗口句柄,在命令行程序中又不想调用windows api创建窗口对象,所以尝试查找控制台下有无可用并且有效的窗口句柄.找了一下,函数原型如下: HWND WINA ...

  8. 无线投屏PC投电视

    http://www.waxrain.com/index.html 电脑投到电视上,看看PPT,显示电脑屏幕完全ok.

  9. [serial]基于select/poll/epoll的串口操作

    转自:http://www.cnblogs.com/darryo/p/selectpollepoll-on-serial-port.html In this article, I will use t ...

  10. Ext.dom.Element 常用方法解析

    Ext.dom.Element 常用方法解析 Ext.Element,Ext.core.Elemen,Ext.dom.Element 这几个类都是一个类,在EXT当中给起了别名而已,这个类到作用主要是 ...