Vector 类存储原理

33 篇文章 1 订阅

Vector 所有的方法都使用了 synchronized 修饰符,即:Vector 线程安全但是性能较低,适用于,适用于多线程环境。

通过源码分析,发现在 Vector 类中有一个 Object[] 类型数组,

    /**
     * The array buffer into which the components of the vector are
     * stored. The capacity of the vector is the length of this array buffer,
     * and is at least large enough to contain all the vector's elements.
     *
     * <p>Any array elements following the last element in the Vector are null.
     *
     * @serial
     */
    protected Object[] elementData;

protected Object[] elementData;

  1. 表面上把数组存储到 Vector 对象中,其实底层依然是把数据存储到 Object 数组中。
  2. 该数组的元素类型是 Object 类型,即是该集合中能且只能存储任意类型的对象。
    • 该集合中只能存储对象,不能存储基本数据类型的值。
    • 在 Java5 之前,必须对基本数据类型进行手动装箱,从 Java5 开始支持自动装箱
  3. 集合类中存储的对象,实际上存储的是对象的引用,而不是对象本身。

Vector 类的操作方法:

增加:

boolean add(Object e);

// Appends the specified element to the end of this Vector

将指定元素添加到此向量的末尾,等价于 addElement 方法

void add(int indiex,Object element);

// Inserts the specified element at the specified position in this Vector.

在此向量的指定位置插入指定的元素

boolean addAll(Collection c);

// Appends all of the elements in the specified Collection to the end of this Vector, in the order that they are returned by the specified

把 c 集合中的元素添加到当前集合对象里

删除:

Object remove(int index);

// Removes the element at the specified position in this Vector.
// return element that was removed

删除指定索引位置的元素,并返回删除之后的元素

boolean remove(Object o);

// Removes the first occurrence of the specified element in this Vector.

删除指定的元素

boolean removeAll(Collection c);

// Removes from this Vector all of its elements that are contained in the specified Collection.

  从此集合中移除包含在指定集合 c中的所有元素

boolean retainAll(Collection c);

// Retains only the elements in this Vector that are contained in the specified Collection.  In other words, removes from this Vector all of its elements that are not contained in the specified Collection.

在此集合中仅保留在指定集合 c 中的元素

void clear();

// Removes all of the elements from this Vector.  The Vector will be empty after this call returns (unless it throws an exception)

清空该集合,相当于 removeAllElements .

修改:

Object set(int index,Object element);

// Replaces the element at the specified position in this Vector with the specified element.
// return the element previously at the specified position.

修改当前集合中指定索引位置的元素,返回被替换的旧的元素

查询:

int size();

// Returns the number of components in this vector.
返回当前集合中存储的元素数

boolean isEmpty();

// Tests if this vector has no components.
判断当前集合中元素个数是否为0

Object get(int index);

// Returns the element at the specified position in this Vector.

查询指定索引位置的元素

Object[] toArray();

// Returns an array containing all of the elements in this Vector in the correct order.

把集合对象转换为 Object 数组
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值