An overview of the

Like ArrayLIst, Vector maintains an array internally. Vector is thread-safe. The method is basically the same as ArrayList, except that synchronized keyword is added to ensure thread safety. The source code of ArrayList can be viewed in detail without detailed analysis.

Vector source code analysis

1. Main fields

 

2. Constructor

 

 

3. Add, delete, modify and check

 

Most of the other methods are similar and will not be described again. Here are the functions of the expansion mechanism:

 

 

Difference between Vector and ArrayList

  1. Most importantly, Vector is thread-safe. ArrayList is not thread-safe
  2. ArrayList can not be set to expand the capacity, default 1.5 times; Vector can be set to 2 times by default
  3. The ArrayList no-argument constructor starts with 0; Vector’s no-argument constructor has an initial capacity of 10

The Vector and the Collections. SynchronizedList

Vector is a class in the java.util package. SynchronizedList is a static inner class in Java.util. Collections.

In a multithreaded scenario can directly use the Vector class, you can also use the Collections. SynchronizedList List (List) method to return a List of thread safety.

Is there a difference between a SynchronizedList and a Vector, and why does the Java API provide thread-safe implementations of these two lists?

SynchronizedList synchronizedList

 

 

 

 

 

From the code, we can see:

  1. Vector is implemented using synchronized methods, and synchronizedList is implemented using synchronized code blocks
  2. ArrayList and Vector differ in how they expand arrays.

However, the listlterator method on the SynchronizedList is not synchronized, but the method lock is applied to the method on the Vector. Therefore, lock manually when traversing SynchronizedList.

 

However, if we want to make our LinkedList thread-safe, we can turn our existing LinkedList directly into a SynchronizedList without changing its underlying data structure, which Vector cannot do. Because the Vector underlying structure uses arrays, this cannot be changed.

The differences are summarized as follows:

  1. SynchronizedList has excellent extensibility and compatibility to convert all List subclasses to thread-safe classes
  2. Using SynchronizedList requires manual synchronization as it traverses
  3. SynchronizedList specifies the lock object