Java集合类源码分析

常用类及源码分析

集合类原理分析
Collection 
List 
Vector

扩充容量的方法 ensureCapacityHelper
很多方法都加入了synchronized同步语句,来保证线程安全
Vector中也允许元素为null
Vector现在已经基本不再使用

ArrayList 

ArrayList是基于数组实现 
不是线程安全的,只能用在单线程环境下
可以通过下标索引直接查找到指定位置的元素,因此查找效率高,但每次插入或删除元素,就要大量地移动元素,插入删除元素的效率低
允许元素为null

LinkedList 

LinkedList是基于双向循环链表实现的,除了可以当做链表来操作外,它还可以当做栈、队列和双端队列来使用
非线程安全的,只在单线程下适合使用
LinkedList中允许元素为null
插入删除效率高,查找效率低

Set 同Collection
HashSet 通过Map中的HashMap实现
TreeSet 通过Map中的TreeMap实现
Map 
Hashtable 

Hashtable同样是基于哈希表实现的,同样每个元素是一个key-value对,其内部也是通过单链表解决冲突问题,容量不足(超过了阀值)时,同样会自动增长。
HashTable在不指定容量的情况下的默认容量为11,而HashMap为16,Hashtable不要求底层数组的容量一定要为2的整数次幂,而HashMap则要求一定为2的整数次幂。
Hashtable扩容时,将容量变为原来的2倍加1,而HashMap扩容时,将容量变为原来的2倍。
Hashtable也是JDK1.0引入的类,是线程安全的,能用于多线程环境中
Hashtable中key和value都不允许为null,而HashMap中key和value都允许为null(key只能有一个为null,而value则可以有多个为null)。

Properties 
HashMap 

HashMap是基于哈希表实现的,每一个元素是一个key-value对,其内部通过单链表解决冲突问题,容量不足(超过了阀值)时,同样会自动增长
HashMap是非线程安全的,只是用于单线程环境下,多线程环境下可以采用concurrent并发包下的ConcurrentHashMap。
HashMap中key和value都允许为null。

TreeMap 

TreeMap是基于红黑树实现 红黑树是一种特殊的二叉排序树
TreeMap是根据key进行排序的,它的排序和定位需要依赖比较器或覆写Comparable接口,也因此不需要key覆写hashCode方法和equals方法
就可以排除掉重复的key,而HashMap的key则需要通过覆写hashCode方法和equals方法来确保没有重复的key。
TreeMap的查询、插入、删除效率均没有HashMap高,一般只有要对key排序时才使用TreeMap。
TreeMap的key不能为null,而HashMap的key可以为null

public interface Collection <E> extends Iterable<E> {
    //1添加
    boolean add(E e);
    boolean addAll(Collection<? extends E> c);
    //2删除
    boolean remove(Object o);
    boolean removeAll(Collection<?> c);
    void clear(); //3判断 boolean contains(Object o); boolean containsAll(Collection<?> c); boolean isEmpty(); //集合是否为空 //4获取 int size(); Iterator<E> iterator(); //迭代器 取出元素方式 //5其它 boolean retainAll(Collection<?> c); //取交集 Object[] toArray(); //转数组 <T> T[] toArray(T[] a); boolean equals(Object o); int hashCode(); }
public interface Iterable<T> {
    Iterator<T> iterator(); //具体集合类返回一个迭代器
}

public interface Iterator<E> {
    boolean hasNext(); //是否还有下个元素
    E next(); //下一个元素
    void remove();
}
public interface List<E> extends Collection<E> {
    //其它方法与Collection中相同
    //1添加
    void add(int index, E element);
    boolean addAll(int index, Collection<? extends E> c);
    //2删除
    E remove(int index);
    //3修改
    E set(int index, E element);
    //4获取
    E get(int index); int indexOf(Object o); int lastIndexOf(Object o); List<E> subList(int fromIndex, int toIndex); ListIterator<E> listIterator(); ListIterator<E> listIterator(int index); }
public class Vector <E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable{
    protected Object[] elementData; //数据数组 
    protected int elementCount; //实际数据的数量
    protected int capacityIncrement; //容量增长系数
    private static final long serialVersionUID = -2767605614048989439L; //序列版本号
    
    //四个不同的构造方法
    // Vector构造函数。默认容量是10。
    public Vector() {
        this(10);
    }
    
    //指定Vector容量大小的构造函数
    public Vector(int initialCapacity) {
        this(initialCapacity, 0);
    }
    
    //指定Vector"容量大小"和"增长系数"的构造函数
    public Vector(int initialCapacity, int capacityIncrement) { super(); if (initialCapacity < 0) throw new IllegalArgumentException("Illegal Capacity: "+initialCapacity); this.elementData = new Object[initialCapacity]; this.capacityIncrement = capacityIncrement; } // 指定集合的Vector构造函数 public Vector(Collection<? extends E> c) { elementData = c.toArray(); elementCount = elementData.length; if (elementData.getClass() != Object[].class) elementData = Arrays.copyOf(elementData, elementCount, Object[].class); } //1增 // 在index位置处插入元素(obj) public synchronized void insertElementAt(E obj, int index) { modCount++; if (index > elementCount) { throw new ArrayIndexOutOfBoundsException(index + " > " + elementCount); } ensureCapacityHelper(elementCount + 1); System.arraycopy(elementData, index, elementData, index + 1, elementCount - index); elementData[index] = obj; elementCount++; } // 将“元素obj”添加到Vector末尾 public synchronized void addElement(E obj) { modCount++; ensureCapacityHelper(elementCount + 1); elementData[elementCount++] = obj; } // 将“元素e”添加到Vector最后。 public synchronized boolean add(E e) { modCount++; ensureCapacityHelper(elementCount + 1); elementData[elementCount++] = e; return true; } // 在index位置添加元素element public void add(int index, E element) { insertElementAt(element, index); } // 将集合c添加到Vector中 public synchronized boolean addAll(Collection<? extends E> c) { modCount++; Object[] a = c.toArray(); int numNew = a.length; ensureCapacityHelper(elementCount + numNew); System.arraycopy(a, 0, elementData, elementCount, numNew); elementCount += numNew; return numNew != 0; } // 从index位置开始,将集合c添加到Vector中 public synchronized boolean addAll(int index, Collection<? extends E> c) { modCount++; if (index < 0 || index > elementCount) throw new ArrayIndexOutOfBoundsException(index); Object[] a = c.toArray(); int numNew = a.length; ensureCapacityHelper(elementCount + numNew); int numMoved = elementCount - index; if (numMoved > 0) System.arraycopy(elementData, index, elementData, index + numNew, numMoved); System.arraycopy(a, 0, elementData, index, numNew); elementCount += numNew; return numNew != 0; } //2删 // 删除index位置的元素 public synchronized void removeElementAt(int index) { modCount++; if (index >= elementCount) { throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount); } else if (index < 0) { throw new ArrayIndexOutOfBoundsException(index); } int j = elementCount - index - 1; if (j > 0) { System.arraycopy(elementData, index + 1, elementData, index, j); } elementCount--; elementData[elementCount] = null; } // 在Vector中查找并删除元素obj 成功的话,返回true;否则,返回false。 public synchronized boolean removeElement(Object obj) { modCount++; int i = indexOf(obj); if (i >= 0) { removeElementAt(i); return true; } return false; } // 删除Vector中的全部元素 public synchronized void removeAllElements() { modCount++; for (int i = 0; i < elementCount; i++) elementData[i] = null; elementCount = 0; } // 删除Vector中的元素o public boolean remove(Object o) { return removeElement(o); } // 删除index位置的元素,并返回index位置的原始值 public synchronized E remove(int index) { modCount++; if (index >= elementCount) throw new ArrayIndexOutOfBoundsException(index); E oldValue = elementData(index); int numMoved = elementCount - index - 1; if (numMoved > 0) System.arraycopy(elementData, index+1, elementData, index, numMoved); elementData[--elementCount] = null; return oldValue; } // 清空Vector public void clear() { removeAllElements(); } // 删除集合c的全部元素 public synchronized boolean removeAll(Collection<?> c) { return super.removeAll(c); } // 删除“非集合c中的元素” public synchronized boolean retainAll(Collection<?> c) { return super.retainAll(c); } // 删除Vector中fromIndex到toIndex的元素 protected synchronized void removeRange(int fromIndex, int toIndex) { modCount++; int numMoved = elementCount - toIndex; System.arraycopy(elementData, toIndex, elementData, fromIndex, numMoved); int newElementCount = elementCount - (toIndex-fromIndex); while (elementCount != newElementCount) elementData[--elementCount] = null; } //3改 // 设置index位置的元素值为obj public synchronized void setElementAt(E obj, int index) { if (index >= elementCount) { throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount); } elementData[index] = obj; } // 设置index位置的值为element。并返回index位置的原始值 public synchronized E set(int index, E element) { if (index >= elementCount) throw new ArrayIndexOutOfBoundsException(index); E oldValue = elementData(index); elementData[index] = element; return oldValue; } //4查 // 返回“Vector的实际大小”,即Vector中元素个数 public synchronized int size() { return elementCount; } // 判断Vector是否为空 public synchronized boolean isEmpty() { return elementCount == 0; } // 返回“Vector中全部元素对应的Enumeration” public Enumeration<E> elements() { return new Enumeration<E>() { int count = 0; public boolean hasMoreElements() { return count < elementCount; } public E nextElement() { synchronized (Vector.this) { if (count < elementCount) { return elementData(count++); } } throw new NoSuchElementException("Vector Enumeration"); } }; } // 返回Vector中是否包含对象(o) public boolean contains(Object o) { return indexOf(o, 0) >= 0; } // 查找并返回元素(o)在Vector中的索引值 public int indexOf(Object o) { return indexOf(o, 0); } // 从index位置开始向后查找元素(o) 若找到,则返回元素的索引值;否则,返回-1 public synchronized int indexOf(Object o, int index) { if (o == null) { for (int i = index ; i < elementCount ; i++) if (elementData[i]==null) return i; } else { for (int i = index ; i < elementCount ; i++) if (o.equals(elementData[i])) return i; } return -1; } // 从后向前查找元素(o)。并返回元素的索引 public synchronized int lastIndexOf(Object o) { return lastIndexOf(o, elementCount-1); } // 从后向前查找元素(o)。开始位置是从前向后的第index个数 若找到,则返回元素的“索引值”;否则,返回-1。 public synchronized int lastIndexOf(Object o, int index) { if (index >= elementCount) throw new IndexOutOfBoundsException(index + " >= "+ elementCount); if (o == null) { for (int i = index; i >= 0; i--) if (elementData[i]==null) return i; } else { for (int i = index; i >= 0; i--) if (o.equals(elementData[i])) return i; } return -1; } // 返回Vector中index位置的元素 若index越界,则抛出异常 public synchronized E elementAt(int index) { if (index >= elementCount) { throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount); } return elementData(index); } // 获取Vector中的第一个元素 若失败,则抛出异常! public synchronized E firstElement() { if (elementCount == 0) { throw new NoSuchElementException(); } return elementData(0); } // 获取Vector中的最后一个元素 若失败,则抛出异常! public synchronized E lastElement() { if (elementCount == 0) { throw new NoSuchElementException(); } return elementData(elementCount - 1); } @SuppressWarnings("unchecked") E elementData(int index) { return (E) elementData[index]; } // 获取index位置的元素 public synchronized E get(int index) { if (index >= elementCount) throw new ArrayIndexOutOfBoundsException(index); return elementData(index); } // 返回Vector是否包含集合c public synchronized boolean containsAll(Collection<?> c) { return super.containsAll(c); } // 获取Vector中fromIndex(包括)到toIndex(不包括)的子集 public synchronized List<E> subList(int fromIndex, int toIndex) { return Collections.synchronizedList(super.subList(fromIndex, toIndex), this); } //5其它 // 返回Object数组 public synchronized Object[] toArray() { return Arrays.copyOf(elementData, elementCount); } // 返回Vector的模板数组。所谓模板数组,即可以将T设为任意的数据类型 @SuppressWarnings("unchecked") public synchronized <T> T[] toArray(T[] a) { if (a.length < elementCount) return (T[]) Arrays.copyOf(elementData, elementCount, a.getClass()); System.arraycopy(elementData, 0, a, 0, elementCount); if (a.length > elementCount) a[elementCount] = null; return a; } // 将数组Vector的全部元素都拷贝到数组anArray中 public synchronized void copyInto(Object[] anArray) { System.arraycopy(elementData, 0, anArray, 0, elementCount); } // 将当前容量值设为实际元素个数 public synchronized void trimToSize() { modCount++; int oldCapacity = elementData.length; if (elementCount < oldCapacity) { elementData = Arrays.copyOf(elementData, elementCount); } } // 确定Vector的容量 public synchronized void ensureCapacity(int minCapacity) { if (minCapacity > 0) { modCount++; ensureCapacityHelper(minCapacity); } } // 确认“Vector容量”的帮助函数 private void ensureCapacityHelper(int minCapacity) { if (minCapacity - elementData.length > 0) grow(minCapacity); } private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; // 当Vector的容量不足以容纳当前的全部元素,增加容量大小。 // 若 容量增量系数>0(即capacityIncrement>0),则将容量增大当capacityIncrement // 否则,将容量增大一倍。 private void grow(int minCapacity) { int oldCapacity = elementData.length; int newCapacity = oldCapacity + ((capacityIncrement > 0) ? capacityIncrement : oldCapacity); if (newCapacity - minCapacity < 0) newCapacity = minCapacity; if (newCapacity - MAX_ARRAY_SIZE > 0) newCapacity = hugeCapacity(minCapacity); elementData = Arrays.copyOf(elementData, newCapacity); } private static int hugeCapacity(int minCapacity) { if (minCapacity < 0) // overflow throw new OutOfMemoryError(); return (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE; } // 设置容量值为 newSize public synchronized void setSize(int newSize) { modCount++; if (newSize > elementCount) { ensureCapacityHelper(newSize); } else { for (int i = newSize ; i < elementCount ; i++) { elementData[i] = null; } } elementCount = newSize; } // 返回“Vector的总的容量” public synchronized int capacity() { return elementData.length; } public synchronized Object clone() { try { @SuppressWarnings("unchecked") Vector<E> v = (Vector<E>) super.clone(); v.elementData = Arrays.copyOf(elementData, elementCount); v.modCount = 0; return v; } catch (CloneNotSupportedException e) { throw new InternalError(); } } public synchronized boolean equals(Object o) { return super.equals(o); } public synchronized int hashCode() { return super.hashCode(); } public synchronized String toString() { return super.toString(); } //写入函数 private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException { final java.io.ObjectOutputStream.PutField fields = s.putFields(); final Object[] data; synchronized (this) { fields.put("capacityIncrement", capacityIncrement); fields.put("elementCount", elementCount); data = elementData.clone(); } fields.put("elementData", data); s.writeFields(); } public synchronized ListIterator<E> listIterator(int

转载于:https://www.cnblogs.com/huanyi0723/p/6171068.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值