`
uule
  • 浏览: 6310869 次
  • 性别: Icon_minigender_1
  • 来自: 一片神奇的土地
社区版块
存档分类
最新评论

Arraylist与Vector

 
阅读更多

ArrayList / Vector

        Object[] elementData

            默认容量10

 

         Object[]  Arrays.copyOf(Object[] original, int newLength)

 

         System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length)

 

          ArrayList 扩容1.5倍

          Vector 扩容2倍

 

 JAVA vector源码

 

// capacity是Vector的默认容量大小。当由于增加数据导致容量增加时,每次容量会增加一倍。
Vector(int capacity)

// capacity是Vector的默认容量大小,capacityIncrement是每次Vector容量增加时的增量值。
Vector(int capacity, int capacityIncrement)

 Vector MyVector = new Vector(100,50);(

创建一个数组类对象MyVector,有100个元素的空间,若空间使用完时,以50个元素空间单位递增

 

1、为什么要了解Java 集合类

 

Java 集合类提供了如线性表,链表和哈希表等基础数据结构的实现,通过它可以实现各种你想要的数据结构,如stack ,queue 等,了解Java 集合类的工作原理可以编出更高效性能的程序,另外了解其工作原理可以更好地使用它,避免因为滥用而出现性能上的问题。事实证明,很多性能上的问题都是因为使用不当引起的。

 

2、Java collection 的继承关系

 

Collection   

├List   

│├LinkedList   

│├ArrayList   

│└Vector   

│   └Stack   

└Set  

└SortedSet

└HashSet

└TreeSet

 

Map   

├Hashtable   

├HashMap 

├SortedMap

  └TreeMap  

└WeakHashMap 

 

 

1、Vector   

 

Vector比ArrayList多了个protected int capacityIncrement; 属性

 

扩容方法:

 

/**
     * 核心方法之一:保证数组的容量,如果没有指定容量的增长的步长,则将原数组容量扩 * 大成原来的两倍,如果指定则按照增长的步长增加容量,并且取 minCapacity 和 *newCapacity 计算出来的最大值进行取值。计算出来的最终容量将作为新数组对象的尺 * 寸,并将原来数组的元素 copy 到新数组里面来。
     *
     * @see #ensureCapacity(int)
     */
    private void ensureCapacityHelper( int minCapacity) {
    int oldCapacity = elementData . length ;
    if (minCapacity > oldCapacity) {
        Object[] oldData = elementData ;
        int newCapacity = ( capacityIncrement > 0) ?
       (oldCapacity + capacityIncrement ) : (oldCapacity * 2);
         if (newCapacity < minCapacity) {
       newCapacity = minCapacity;
        }
            elementData = Arrays.copyOf ( elementData , newCapacity);
    }
    }

  

Vector 使用时需要注意的问题

1) Vector 使用时,最好能够预期需要存放元素的个数,这样可以避免数组长度频繁的改变而引起数据的 copy 带来的开销,同时会引起内存大小的增加。

2 )使用 Vector 需要知道 Vector 是线程安全的。因此,在使用时,最好是考虑这个对象会不会因为多个线程访问该 Vector 对象,如果确认只有单个线程访问,则可以用 ArrayList 来代替 Vector 。

 

 

2、ArrayList:

 

public void ensureCapacity(int minCapacity) {
	modCount++;
	int oldCapacity = elementData.length;
	if (minCapacity > oldCapacity) {
	    Object oldData[] = elementData;
	    int newCapacity = (oldCapacity * 3)/2 + 1;
    	    if (newCapacity < minCapacity)
		newCapacity = minCapacity;
            // minCapacity is usually close to size, so this is a win:
            elementData = Arrays.copyOf(elementData, newCapacity);
	}
    }

 Vector和ArrayList在使用上非常相似,都可用来表示一组数量可变的对象应用的集合,并且可以随机地访问其中的元素。 

Vector的方法都是同步的(Synchronized),是线程安全的(thread-safe),

ArrayList的方法不是,由于线程的同步必然要影响性能,因此,ArrayList的性能比Vector好。

当Vector或ArrayList中的元素超过它的初始大小时,Vector会将它的容量翻倍,而ArrayList只增加50%的大小,这样,ArrayList就有利于节约内存空间。

 

 

 

Arrays.copyOf(elementData, size)

 

/**<Object> Object[] java.util.Arrays.copyOf(Object[] original, int newLength)
Copies the specified array, truncating or padding with nulls (if necessary) so the copy has the specified length. For all indices that are valid in both the original array and the copy, the two arrays will contain identical values. For any indices that are valid in the copy but not the original, the copy will contain null. Such indices will exist if and only if the specified length is greater than that of the original array. The resulting array is of exactly the same class as the original array.

Parameters:
original the array to be copied
newLength the length of the copy to be returned
Returns:
a copy of the original array, truncated or padded with nulls to obtain the specified length
*/

 

Arrays.copyOf(elementData, size, Object[].class)

 

/**Parameters:
original the array to be copied
newLength the length of the copy to be returned
newType the class of the copy to be returned
*/

 

 

System.arraycopy(elementData, 0, a, 0, size)

 

/**
void java.lang.System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
Copies an array from the specified source array, beginning at the specified position, to the specified position of the destination array. A subsequence of array components are copied from the source array referenced by src to the destination array referenced by dest. The number of components copied is equal to the length argument. The components at positions srcPos through srcPos+length-1 in the source array are copied into positions destPos through destPos+length-1, respectively, of the destination array. 

If the src and dest arguments refer to the same array object, then the copying is performed as if the components at positions srcPos through srcPos+length-1 were first copied to a temporary array with length components and then the contents of the temporary array were copied into positions destPos through destPos+length-1 of the destination array. 

Parameters:
src the source array.
srcPos starting position in the source array.
dest the destination array.
destPos starting position in the destination data.
length the number of array elements to be copied.

*/

 

 

几个主要方法:

 

 public Object[] toArray() {
        return Arrays.copyOf(elementData, size);
    }

 

 

 /**
     * Inserts the specified element at the specified position in this
     * list. Shifts the element currently at that position (if any) and
     * any subsequent elements to the right (adds one to their indices).
     *
     * @param index index at which the specified element is to be inserted
     * @param element element to be inserted
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public void add(int index, E element) {
	if (index > size || index < 0)
	    throw new IndexOutOfBoundsException(
		"Index: "+index+", Size: "+size);

	ensureCapacity(size+1);  // Increments modCount!!
	System.arraycopy(elementData, index, elementData, index + 1,
			 size - index);
	elementData[index] = element;
	size++;
    }

 

 

/**
     * Removes the element at the specified position in this list.
     * Shifts any subsequent elements to the left (subtracts one from their
     * indices).
     *
     * @param index the index of the element to be removed
     * @return the element that was removed from the list
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public E remove(int index) {
	RangeCheck(index);

	modCount++;
	E oldValue = (E) elementData[index];

	int numMoved = size - index - 1;
	if (numMoved > 0)
	    System.arraycopy(elementData, index+1, elementData, index,
			     numMoved);
	elementData[--size] = null; // Let gc do its work

	return oldValue;
    }

 

 

/**
     * Appends all of the elements in the specified collection to the end of
     * this list, in the order that they are returned by the
     * specified collection's Iterator.  The behavior of this operation is
     * undefined if the specified collection is modified while the operation
     * is in progress.  (This implies that the behavior of this call is
     * undefined if the specified collection is this list, and this
     * list is nonempty.)
     *
     * @param c collection containing elements to be added to this list
     * @return <tt>true</tt> if this list changed as a result of the call
     * @throws NullPointerException if the specified collection is null
     */
    public boolean addAll(Collection<? extends E> c) {
	Object[] a = c.toArray();
        int numNew = a.length;
	ensureCapacity(size + numNew);  // Increments modCount
        System.arraycopy(a, 0, elementData, size, numNew);
        size += numNew;
	return numNew != 0;
    }

 

 

/**
     * Inserts all of the elements in the specified collection into this
     * list, starting at the specified position.  Shifts the element
     * currently at that position (if any) and any subsequent elements to
     * the right (increases their indices).  The new elements will appear
     * in the list in the order that they are returned by the
     * specified collection's iterator.
     *
     * @param index index at which to insert the first element from the
     *              specified collection
     * @param c collection containing elements to be added to this list
     * @return <tt>true</tt> if this list changed as a result of the call
     * @throws IndexOutOfBoundsException {@inheritDoc}
     * @throws NullPointerException if the specified collection is null
     */
    public boolean addAll(int index, Collection<? extends E> c) {
	if (index > size || index < 0)
	    throw new IndexOutOfBoundsException(
		"Index: " + index + ", Size: " + size);

	Object[] a = c.toArray();
	int numNew = a.length;
	ensureCapacity(size + numNew);  // Increments modCount

	int numMoved = size - index;
	if (numMoved > 0)
	    System.arraycopy(elementData, index, elementData, index + numNew,
			     numMoved);

        System.arraycopy(a, 0, elementData, index, numNew);
	size += numNew;
	return numNew != 0;
    }

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics