Vector
Vector is an older implementation of the List interface, very similar to ArrayList, but with all its methods synchronized, meaning it is safe to use across multiple threads simultaneously.
1. What is Vector?
Vector is an older implementation of the List interface, very similar to ArrayList, but with all its methods synchronized, meaning it is safe to use across multiple threads simultaneously.
2. Why is it used?
Vector is used in situations where thread safety for list operations is genuinely required, though in modern Java, other approaches are often preferred for new projects.
3. Real-Life Example
Think of a single shared notice board where only one person is allowed to write on it at a time, ensuring nothing gets overwritten or lost due to two people writing simultaneously. Vector behaves similarly across threads.
4. Syntax
javaVector<DataType> vectorName = new Vector<>();
5. Example Program
javaimport java.util.Vector; public class VectorDemo { public static void main(String[] args) { Vector<String> colors = new Vector<>(); colors.add("Red"); colors.add("Blue"); System.out.println(colors); } }
Output:
[Red, Blue]6. Key Points to Remember
Vectoris synchronized (thread-safe), unlikeArrayList.- Because of this synchronization,
Vectoris generally slower thanArrayListin single-threaded programs. Vectoris considered a legacy class;ArrayListcombined with explicit synchronization (when needed) is usually preferred today.