On Vector

On Vector

In the previous article, we have talked about thread-unsafe ArrayList and LinkedList. Today we will talk about a thread-safe list container. He is Vector. His bottom layer is implemented using arrays like ArrayList, but different from ArrayList. The thread is not safe. The public methods in Vector are basically with the synchronized keyword. Although some methods are non-synchronized, the synchronized method is always called internally to ensure the thread safety of the entire method, even if it is a sublist returned by the subList method. It is also through the SynchronizedList of the Collections class to ensure that the returned sublist is also thread-safe:

public synchronized List<E> subList(int fromIndex, int toIndex) {
    return Collections.synchronizedList(super.subList(fromIndex, toIndex), this);
}

Next, let's introduce the construction method of Vector. Vector provides four construction methods for us. The first three are basically calling single parameters without parameters and passing a default capacity value, and calling double parameters with single parameters and passing a default capacity value.

Vector();

public Vector() {
    //调用单参的构造方法,并传递一个初始容量值10
    this(10);
}

Vector(int initialCapacity);

public Vector(int initialCapacity) {
    //调用双参的构造方法,并传递一个默认增量值0,增量值为0,代表每次扩容,容量会直接翻倍
    this(initialCapacity, 0);
}

Vector(int initialCapacity, int capacityIncrement);

public Vector(int initialCapacity, int capacityIncrement) {
    super();
    if (initialCapacity < 0)
        throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity);
    this.elementData = new Object[initialCapacity];
    this.capacityIncrement = capacityIncrement;
}

The fourth construction method is to initialize the elements of the vector list according to the incoming collection object

Vector(Collection<? extends E> c);

public Vector(Collection<? extends E> c) {
    elementData = c.toArray();
    elementCount = elementData.length;
    // c.toArray might (incorrectly) not return Object[] (see 6260652)
    //如果通过toArray方法转换得到的数组类型不是Object[],则进行二次转化
    if (elementData.getClass() != Object[].class)
        elementData = Arrays.copyOf(elementData, elementCount, Object[].class);
}

Before explaining the method, let's take a look at Vector's capacity expansion mechanism. Vector provides a public method ensureCapacity (int minCapacity), through which you can pass in the minimum capacity value required by a list (but the resulting new capacity may not Not this value), and then do a simple check, and further call the internal private ensureCapacityHelper (int minCapacity) method for further judgment, if the value is less than the current list capacity of the list (the total number of non-list elements), will not enter the expansion method In grow, after entering the grow method, the specific expansion process begins. For details, please see the following source code:

public synchronized void ensureCapacity(int minCapacity) {
    if (minCapacity > 0) {
        modCount++;
        ensureCapacityHelper(minCapacity);
    }
}
private void ensureCapacityHelper(int minCapacity) {
    // overflow-conscious code
    if (minCapacity - elementData.length > 0)
        grow(minCapacity);
}
private void grow(int minCapacity) {
    // overflow-conscious code
    int oldCapacity = elementData.length;
    //按内置规则扩容获得新的容量值,如果增量变量为0,容量翻倍,否则增加增量变量指定的增量值
    int newCapacity = oldCapacity + ((capacityIncrement > 0) ? capacityIncrement : oldCapacity);
    //将新的容量值与传入的最小容量作比较,如果最小容量值大于新的容量值,则将最小容量值作为新的容量值,否则使用内置扩容规则获得的容量值
    if (newCapacity - minCapacity < 0)
        newCapacity = minCapacity;
    //最后将容量值与数组最大容量值(最大整型值-8)做比较
    //数组作为一个对象,需要一定的内存存储对象头信息,对象头信息最大占用内存不可超过8字节
    if (newCapacity - MAX_ARRAY_SIZE > 0)
        newCapacity = hugeCapacity(minCapacity);
    //使用新容量和原列表生成新的列表并将元素进行拷贝,内部最终调用System.arraycopy方法进行元素拷贝
    elementData = Arrays.copyOf(elementData, newCapacity);
}

After talking about Vector's expansion rules, the following formally introduces the methods in Vector

add(E element); addElement(E element);

Both of these methods are to insert new elements into the end of the vector list. They are both synchronous methods. The difference is that the return value of add is a boolean type, and addElement has no return value.

add(int index, E element); insertElementAt(E element, int index);

These two methods can be said to be completely the same. In the add method, only the insertElementAt method is called. Although add is an asynchronous method, insertElementAt is a synchronous method.

addAll([int index,] Collection<? extends E> c);

This method is used to store all the elements in the collection into the vector list. This method has two overload methods, single parameter and double parameter, both are synchronous methods. The single parameter method is directly inserted into the tail, and the double parameter method can be specified at the index Position insert

remove(int index);

This method is used to delete the value of the specified index position in the vector list and return the deleted element. This method is a synchronous method

remove(Object o); removeElement(Object o); removeElementAt(int index);

These three methods are used to delete the elements in the vector list, where remove is asynchronous, and the remaining two methods are synchronized, but the remove method of synchronization is called in the remove method. The index of the element to be deleted, and if it is found, the removeElementAt method is called to delete the element value at the specified index position

removeAll(Collection<?> c)

This method is used to delete all the elements specified in the incoming collection, is a synchronous method

retainAll(Collection<?> c);

This method is used to retain all the elements specified in the incoming collection, that is, delete all elements outside the specified collection, this method is a synchronous method

clear(); removeAllElements();

These two methods are used to delete all elements in the vector list. The clear method is asynchronous, and the synchronized removeAllElements method is called internally.

removeRange(int fromIndex, int toIndex);

This method is used to remove all elements of the specified index range in the vector list. This method is a synchronous method

removeIf(Predicate<? super E> filter);

This method is used to remove the elements in the vector list that meet the specified conditions. This method is a synchronous method. The following uses an anonymous inner class and Lambda to make a simple demonstration:

Vector<Integer> list = new Vector<>();
list.add(1);list.add(2);list.add(3);list.add(4);list.add(5);
System.out.println(list);
//如果不会使用Lambda表达式,则需要new Predicate接口对象并实现内部的test方法
list.removeIf(x -> x < 3);
System.out.println(list);
//对应的运行结果
[1, 2, 3, 4, 5]
[3, 4, 5]

set(int index, E element); setElementAt(E element, int index);

These two methods are used to replace the element value of the specified index position in the vector list. They are both synchronous methods. The difference is that the set method returns the replaced element value, and setElementAt has no return value.

replaceAll(UnaryOperator operator);

This method is used to perform the operation of specifying the hook function on all elements in the vector list, and will save the changes made to the element. This method is a synchronous method. The following uses an anonymous inner class combined with Lambda expressions to make a simple demonstration :

Vector<Integer> list = new Vector<>();
list.add(1);list.add(2);list.add(3);list.add(4);list.add(5);
System.out.println(list);
//或者使用UnaryOperator接口创建匿名内部类,并实现apply方法亦可
list.replaceAll(x -> x + 2);
System.out.println(list);
//对应的运行结果
[1, 2, 3, 4, 5]
[3, 4, 5, 6, 7]

forEach()

This method is used to perform the operation of specifying the hook function on all elements in the vector list, but it will not save the modifications made to the elements. This method is a synchronous method. The following is a simple demonstration:

Vector<Integer> list = new Vector<>();
list.add(1);list.add(2);list.add(3);list.add(4);list.add(5);
System.out.println(list);
//或者使用Consumer接口创建匿名内部类,并实现accept方法亦可
list.forEach(x -> System.out.println(x += 2));
System.out.println(list);
//对应的运行结果
[1, 2, 3, 4, 5]
3
4
5
6
7
[1, 2, 3, 4, 5]

get(int index); elementAt(int index);

These two methods are the same, used to return the value of the element at the specified position in the vector list, both are synchronous methods

elements();

This method is used to return the enumeration object of the vector list. This method is a synchronous method. You can use the returned enumeration object for simple iterative traversal. The following is a simple application:

Vector<Integer> list = new Vector<>();
list.add(1);list.add(2);list.add(3);list.add(4);list.add(5);
Enumeration<Integer> elements = list.elements();
while (elements.hasMoreElements()){
    System.out.println(elements.nextElement());
}

firstElement (); lastElement ();

These two methods are used to return the first element and the tail element in the vector list, respectively, are both synchronous methods

indexOf(Object o); lastIndexOf(Object o);

These two methods are used to return the index value of the first and last occurrence of the specified element in the vector list, respectively, are both synchronous methods

lastIndexOf(Object o, int index);

This method adds an index value on the basis of lastIndexOf (Object o), which is used to find the index value of the last occurrence of the specified element at the position before the specified index value.

iterator();

This method is used to return an ordinary iterator object of the vector list. The iterator provides hasNext, next, remove, forEachRemaining methods for operating on elements, and the iterator method is a synchronous method.

listIterator([int index]);

This method is used to return the enhanced iterator object of the vector list, which provides all the functions of the ordinary iterator. In addition, there are hasPrevious, nextIndex, previousIndex, previous, set, add methods, and you can also specify the starting iteration position through the index parameter The listIterator method is a synchronous method

spliterator ();

This method is used to convert the vector list into a divisible array object. The converted object can be split multiple times by calling trySplit (divided into five and five), which is suitable for multi-threaded operations on large vector lists. A simple demonstration of the split process:

Vector<Integer> list = new Vector<>();
list.add(1);list.add(2);list.add(3);list.add(4);list.add(5);
list.add(6);list.add(7);list.add(8);list.add(9);list.add(0);
Spliterator<Integer> part1 = list.spliterator();
Spliterator<Integer> part2 = part1.trySplit();
Spliterator<Integer> part3 = part1.trySplit();
Spliterator<Integer> part4 = part2.trySplit();
part1.forEachRemaining(x-> System.out.print(x+" "));
System.out.println();
part2.forEachRemaining(x-> System.out.print(x+" "));
System.out.println();
part3.forEachRemaining(x-> System.out.print(x+" "));
System.out.println();
part4.forEachRemaining(x-> System.out.print(x+" "));
//对应的操作结果
8 9 0 
3 4 5 
6 7 
1 2 

capacity();

This method is used to return the capacity value of the vector list (elementData.length), this method is a synchronous method

clone();

This method is used to return a shallow clone object of a vector list, this method is a synchronous method

contains(Object o);

This method is used to determine whether the specified element is included in the vector list. This method is an asynchronous method, but internally calls the synchronized indexOf method.

containsAll(Collection<?> c);

This method is used to determine whether the vector list contains all the elements of the incoming collection, this method is a synchronous method

copyInto(Object[] array);

This method is used to copy all the element values ​​of the vector list to the incoming array. This method is a synchronous method

equals(Object o);

This method is used to determine whether the incoming element is equal to the current element (the value is equal, not necessarily the address is equal), this method is a synchronous method

isEmpty();

This method is used to determine whether there is an element in the vector list, mainly based on the elementCount attribute value to determine, this method is a synchronous method

setSize(int size);

This method is used to control the total number of elements in the vector list within the incoming size. If the size is greater than the total number of elements in the current list (elementCount), then the null of the elementCount-size range is used as a list element (you can see from the vector list here The existence of the element cannot be judged based on whether it is null, but needs to be judged based on elementCount), if the incoming size is less than the total number of list elements, then the value of size-elementCount is set to null, and finally elementCount = size value , The method is a synchronous method

size();

This method is used to return the total number of elements in the vector list (elementCount), this method is a synchronous method

sort(Comparator<? super E> c);

This method is used to sort all the elements in the vector list according to the rules of the hook function. This method is a synchronous method. The following is a simple demonstration of this method:

Vector<Integer> list = new Vector<>();
list.add(1);list.add(4);list.add(5);list.add(2);list.add(3);
list.add(8);list.add(9);list.add(0);list.add(6);list.add(7);
System.out.println(list);
//或者使用Comparator接口创建匿名内部类,并实现compare方法亦可
list.sort((o1,o2) -> o1 - o2);
System.out.println(list);

subList(int fromIndex, int toIndex);

This method is used to return the sub-list object within the specified range of the current vector list. This method is a synchronous method. It should be noted that the final returned list object is still the entire vector list object, but the offset attribute is added, so yes The operations of the child list will be reflected in the parent list

toArray(T[] a);

This method is used to obtain the array object of the vector list and convert it to the array type corresponding to the parameter. This method is a synchronous method. The following is a simple use of this method:

//如果直接调用list.toArray()方法,等同于list.toArray(new Object[0]);
String[] strs = list.toArray(new String[0]);

trimToSize();

This method is used to adjust the capacity of the vector list to the total number of list elements. A new array object will be generated during the adjustment. This method is a synchronous method.
If it is helpful to you
, please like it or give a reward. Hey , it is not easy to organize, please Respect the blogger's labor achievements

Guess you like

Origin www.cnblogs.com/Mango-Tree/p/Vector.html