在根据 SonarQube 建议更改一些代码时,我了解了以下几行:
- Automatic Increase in Capacity A Vector defaults to doubling size of its array . While when you insert an element into the ArrayList ,it increases its Array size by 50%.
现在我想知道是否需要将 Vector 替换为 ArrayList 是否有可能无法正常执行代码。
请记住,现有 Vector 并未执行任何 Thead 安全工作。
问题:
ArrayList 是否有足够的能力像 vector 一样调整大小?
在除同步之外的任何情况下,用 ArrayList 替换 Vector 是否安全?
是否有 Vector 的任何精确替换(不期望线程安全)
请随时更新问题或提出任何问题。
最佳答案
Vector
和ArrayList
的区别是这样的:
Vector
是同步的,而ArrayList
是不同步的。所以,Vector 是线程安全的。Vector
很慢,因为它是线程安全的。相比之下,ArrayList
速度很快,因为它是非同步的。默认情况下,
Vector
增长为其数组大小的两倍。当您将一个元素插入到ArrayList
中时,它会将其数组大小增加 50%。数组列表:
/** * Increases the capacity to ensure that it can hold at least the * number of elements specified by the minimum capacity argument. * * @param minCapacity the desired minimum capacity */ private void grow(int minCapacity) { // overflow-conscious code int oldCapacity = elementData.length; int newCapacity = oldCapacity + (oldCapacity >> 1); // 50% if (newCapacity - minCapacity < 0) newCapacity = minCapacity; if (newCapacity - MAX_ARRAY_SIZE > 0) newCapacity = hugeCapacity(minCapacity); // minCapacity is usually close to size, so this is a win: elementData = Arrays.copyOf(elementData, newCapacity); }
vector :
private void grow(int minCapacity) { // overflow-conscious code int oldCapacity = elementData.length; int newCapacity = oldCapacity + ((capacityIncrement > 0) ? capacityIncrement : oldCapacity); // default 100% if (newCapacity - minCapacity < 0) newCapacity = minCapacity; if (newCapacity - MAX_ARRAY_SIZE > 0) newCapacity = hugeCapacity(minCapacity); elementData = Arrays.copyOf(elementData, newCapacity); }
ArrayList 没有定义增量大小。 vector 定义增量大小。
/** * The amount by which the capacity of the vector is automatically * incremented when its size becomes greater than its capacity. If * the capacity increment is less than or equal to zero, the capacity * of the vector is doubled each time it needs to grow. * * @serial */ protected int capacityIncrement;
基于以上:
ArrayList
不能像Vector
一样调整大小。ArrayList
不是线程安全的。不能直接在多线程中用ArrayList
替换Vector
。它可以在单线程中用
ArrayList
代替Vector
。因为Vector
和ArrayList
的声明:public class Vector<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable
关于java - 如何像 Vector 一样将 ArrayList 大小增加到 100%,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36081886/