Vector和ArrayList区别

来源:互联网 发布:pat知乎 编辑:程序博客网 时间:2024/05/20 22:28

Vector和ArrayList区别:

1、线程安全:Vector线程安全、ArrayList线程非安全;

2、数据增长:Vector增长一倍、ArrayList增长1/2倍;

3.、存储形式:Vector是通用容器-可变长度、ArrayList数组列表

如果涉及到堆栈,队列等操作,应该考虑用Vector,
对于需要快速插入,删除元素,应该使用LinkedList,
如果需要快速随机访问元素,应该使用ArrayList。

同步问题:

Vector源码:

 public int indexOf(Object o) {return indexOf(o, 0);    }    /**     * Returns the index of the first occurrence of the specified element in     * this vector, searching forwards from {@code index}, or returns -1 if     * the element is not found.     * More formally, returns the lowest index {@code i} such that     * <tt>(i >= index && (o==null ? get(i)==null : o.equals(get(i))))</tt>,     * or -1 if there is no such index.     *     * @param o element to search for     * @param index index to start searching from     * @return the index of the first occurrence of the element in     *         this vector at position {@code index} or later in the vector;     *         {@code -1} if the element is not found.     * @throws IndexOutOfBoundsException if the specified index is negative     * @see     Object#equals(Object)     */    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;    }
<pre name="code" class="java">public synchronized E firstElement() {if (elementCount == 0) {    throw new NoSuchElementException();}return (E)elementData[0];    }


ArrayList源码:

/**     * Returns <tt>true</tt> if this list contains no elements.     *     * @return <tt>true</tt> if this list contains no elements     */    public boolean isEmpty() {return size == 0;    }
/**     * Returns the index of the first occurrence of the specified element     * in this list, or -1 if this list does not contain the element.     * More formally, returns the lowest index <tt>i</tt> such that     * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,     * or -1 if there is no such index.     */    public int indexOf(Object o) {if (o == null) {    for (int i = 0; i < size; i++)if (elementData[i]==null)    return i;} else {    for (int i = 0; i < size; i++)if (o.equals(elementData[i]))    return i;}return -1;    }




0 0
原创粉丝点击