Java源码解析-JDK源码

所需积分/C币:21 2017-03-15 08:52:31 599KB PDF

此文档包含了Java源码,也就是我们平常使用的JDK中的List、Map、Set以及其他的东西的详解,在面试中经常被问到这些内容。
Java源码解析 Java源码之 ArrayList Java源码之 ArrayList 转载请注明出处http://blog.csdnnet/itismelzp/article/details/50371326 Arraylist概述 ArrayList就是动态数组,用MSDN中的说法,就是Aray的复杂版本,它提供了动态的增加和减少元素 实现了 ICollection和List接口,灵活的设置数组的大小等好处。 Array List'位于API文档的 ava.util.ArrayList。实现了所有可选列表操作,并允许包括nu在内的所有元 素。除了实现List接口外,此类还提供一些方法来操作内部用来存储列表的数组的大小。(此类大致上等 同于 Vector类,除了此类是不同步的。) 源码 1头文件 package java. uti import java. ioIOEXception import java. io. InvalidObjectException import java. io ObjectInputStream: import java. io ObjectOutputStream; import java. io Serializable import java. lang reflect Array import libcore. util.EmptyArray 2:继承与实现关系 public class ArrayList< E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java. io Serializable 3属性 本文档使用看云构建 Java源码解析 默认初始容量 private static final int DEFAULT CAPACITY= 10 大大 Shared empty array instance used for empty instances *空对象数组 private static final Object[] EMPTY_ELEMENTDATA=0; 默认大小的空对象数组 private static final Object[] DEFAULTCAPACITYEMPTY_ELEMENTDATA =0 大太 数据存放数组 transient Object[ elementData; / non-private to simplify nested class access 包括元素个数 rivate int size 4.构造函数(共3个) 本文档使用看云构建 Java源码解析 构造方法一: *用指定容量构造 public Array List(int initialCapacity) if( initialCapacity>0){∥非法容量 this elementData= new Object[initialCapacity 3 else if (initial Capacity ==0)f this elementData EMPTY ELEMENTDATA f else i throw new IllegalArgument Exception ("Illegal Capacity: " initialCapacity) 构造方法二 用默认默认空数组构造 public arrayList i this elementData DEFAULTCAPACITY EMPTY ELEMENTDATA 构造方法三 用指定集合c构造 public ArrayList(Collection<? extends E> c)( elementData c toArray( if ((size =element Data length)! O)[ ∥/将c中的元素复制到 elementData if (element Data. getClassO! Object[ class elementData= Arrays.copy Of(elementData, size, Object[]. class): else ∥/c是空的,用空数组对象构造 this elementData= EMPTY ElemeNtdata 5.方法 (1)add添加(插入)方法 本文档使用看云构建 Java源码解析 指定的元素e添加到尾部 public boolean add(E e) ensure CapacityInternal(size+1);/size+1,如果容量不够会进行扩容 elementData[size++]=e;加到未尾 return true 在指定的位置插入元素 public void add (int index, E element)( ange Check ForAdd( index);∥/检查插入位置合法性 ensure CapacityInternal(size+1);/size+1,如果容量不够会进行扩容 System. arraycopy(element Data, index, elementData, index +1, size- index);//将 Findex后的数据后移 elementData [index]= element; size++ (2)列表->数组 toArray方法 大大 将列表转化为数组,并将你数组返回 public Object[ toArray(i return Arrays. copyof(elementData, size) (3)扩容策略 ad方法添加元素时如果容量不够时,会调用grow方法进行扩睿, ArrayList的扩容策略是 新容量扩大为原来的15倍 本文档使用看云构建 Java源码解析 private void ensure Capacitylnternal(int min Capacity)i if (elementData== DEFAULTCAPACITY EMPTY ELEMENTDATA)I min Capacity= Math. max(DEFAULT_ CAPACITY, min Capacity) ensure ExplicitCapacity(min Capacity) private void ensure Explicit Capacity(int min Capacity)( mod Count++ ∥/容量不足 if (min Capacity-elementData length > O grow(min Capacity ) *扩容方法 private void grow(int min Capacity)( // overflow-conscious code int old Capacity elementData length: int new Capacity old Capacity +(old Capacity >>1);//(1+0.5) if (new Capacity- min Capacity O) new Capacity min Capacity if( newCapacity-MAX_ARRAY SIZE>0)已达到最大容量,无法扩容 new Capacity= huge Capacity(min Capacity) / min Capacity is usually close to size, so this is a win elementData Arrays copyOf(elementData, new Capacity) 其他方法其实都比较简单,这里不再列举。 下面是 Arraylist的源码 Copyright (c)1997, 2013, Oracle and/ or its affiliates. All rights reserved ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms 本文档使用看云构建 Java源码解析 package java.util import java. util. function. consumer import java. util. function Predicate import java. util. function. UnaryOperator; Resizable-array implementation of the <tt> Lists/tt> interface. Implements all optional list operations, and permits all elements, including <tt>null</tt>. In addition to implementing the <tt> List</tt> interface, this class provides methods to manipulate the size of the array that is used internally to store the list. ( This class is roughly equivalent to <tt> Vector</tt>, except that it is unsynchronized. <p>The <tt>size</tt>, <tt> isEmpty </tt>, <tt>get</tt>,<tt>set</tt> *<tt>iterator </tt>, and <tt> listiterator</tt> operations run in constant time. The <tt> add</tt> operation runs in <i> amortized constant time </i>, that is, adding n elements requires O(n)time. All of the other operations run in linear time (roughly speaking). The constant factor is low compared to that for the <tt> LinkedList</tt> implementation <p>Each <tt> Array List</tt> instance has a <i> capacity </i>. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically. The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost *<p> An application can increase the capacity of an <tt> array List </tt> instance before adding a large number of elements using the <tt> ensure Capacity</tt> operation. this may reduce the amount of incremental reallocation k <p><strong> Note that this implementation is not synchronized. </strong> If multiple threads access an <tt> array list </tt> instance concurrent and at least one of the threads modifies the list structurally it <i>must</i> be synchronized externally. (A structural modification is any operation that adds or deletes one or more elements, or explicitly resizes the backing array; merely setting the value of an element is not a structural modification. This is typically accomplished by synchronizing on some object that naturally encapsulates the list If no such object exists, the list should be "wrapped"using the (@ link Collections# synchronized List Collections. synchronizedList method. This is best done at creation time, to prevent accidental unsynchronized access to the list: < pre> List list Collections synchronizedList(new ArrayList();/pre> 本文档使用看云构建 Java源码解析 <p><a name="fail-fast"> The iterators returned by this class's [@link #iterator() iterator) and [@link # listiterator (int) listIterator methods are <em>fail-fast</em>: </a> if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own [@link ListIterator#remove remove]or [ link ListIterator#add(Object)add) methods, the iterator will throw a [@link ConcurrentModification Exception). Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather h than risking arbitrary, non-deterministic behavior at an undetermined time in the future *<p>Note that the fail-fast behavior of an iterator cannot be guaranteed R as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw (@code ConcurrentModificationException] on a best-effort basis therefore, it would be wrong to write a program that depended on this exception for its correctness: <i> the fail-fast behavior of iterators should be used only to detect bugs. </i> *<p>This class is a member of the <a href="(@docRoot)//technotesguides/collections/index. html"> Java Collections Framework</a> author Josh Bloch 大@ author Neal after 大@ see Collection asee List *@see Linked List see∨ ector *@since 1.2 public class Array List<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java. io Serializable private static final long serialVersionUID=8683452581122892189L Default initial capacity private static final int DEFAULT_CAPACITY= 10; 火大 Shared empty array instance used for empty instances private static final Object[] EMPTY_ELEMENTDATA =11 大大 Shared empty array instance used for default sized empty instances We distinguish this from empty elementdata to know how much to inflate when first element is added private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA =0 本文档使用看云构建 Java源码解析 大 The array buffer into which the elements of the array list are stored The capacity of the ArrayList is the length of this array buffer. Any empty array list with element Data == DEFAULTCAPACITY EMPTY ELEMENTDATA will be expanded to DEFAULT_ CAPACITY when the first element is added transient Object[ elementData; / non-private to simplify nested class access 大大 The size of the array List(the number of elements it contains x@serial private int size 大大 Constructs an empty list with the specified initial capacity * @param initial Capacity the initial capacity of the list k@throws IllegalArgumentException if the specified initial capacity IS negative public array List(int initial Capacity)( if (initial Capacity>0)( this elementData new Object[initialCapacityl F else if (initial Capacity==0)( this elementData EMPTY ELEMENTDATA else throw new IllegalArgumentException(" Illegal Capacity: " initialCapacity): Constructs an empty list with an initial capacity of ten public Array Listo t this elementData= DEFAULTCAPACITY EMPTY ELEMENTDATA Constructs a list containing the elements of the specified collection, in the order they are returned by the collection 's erator param c the collection whose elements are to be placed into this list @throws NullPointer Exception if the specified collection is null public Array List(Collection<? extends E> c) elementData= c toArray o if ((size elementData length)!=0)i //c toArray might (incorrectly) not return Object[](see 6260652 if (elementData getClass(!= Object[]. class) element Data Arrays copy Of(element Data, size, object[]. class); 本文档使用看云构建

...展开详情

评论 下载该资源后可以进行评论 5

sl1655886404 确实表交贵啊
2018-04-21
回复
dreamertn9527 表示有些贵!
2018-03-06
回复
duguoqing_not 啥也没下载下来
2018-01-02
回复
墨彦93 为毛我点下载直接404啊
2017-11-23
回复
xianyualwaysisxianyu 没有concurrentHashmap
2017-08-18
回复
img
Terence Jing
  • 签到新秀

    累计签到获取,不积跬步,无以至千里,继续坚持!

关注 私信 TA的资源

上传资源赚积分,得勋章
相关内容推荐