Vector vs ArrayList in Java

 

Sent by Copilot:

ArrayList vs. Vector in Java

Both ArrayList and Vector are part of the Java Collections Framework and implement the List interface. They are used to store dynamically resizable arrays of objects. However, there are some key differences between them:

1. Synchronization

2. Performance

3. Growth Rate

4. Legacy

5. Traversal

Example of ArrayList

Java
import java.util.ArrayList;
import java.util.Iterator;

public class ArrayListExample {
    public static void main(String[] args) {
        ArrayList<String> arrayList = new ArrayList<>();
        arrayList.add("Apple");
        arrayList.add("Banana");
        arrayList.add("Orange");

        // Traversing elements using Iterator
        Iterator<String> iterator = arrayList.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }
}

Example of Vector

Java
import java.util.Vector;
import java.util.Enumeration;

public class VectorExample {
    public static void main(String[] args) {
        Vector<String> vector = new Vector<>();
        vector.add("Apple");
        vector.add("Banana");
        vector.add("Orange");

        // Traversing elements using Enumeration
        Enumeration<String> enumeration = vector.elements();
        while (enumeration.hasMoreElements()) {
            System.out.println(enumeration.nextElement());
        }
    }
}

When to Use Which?

  • Use ArrayList: When you need a fast, non-synchronized list for single-threaded applications.
  • Use Vector: When you need a thread-safe list for multi-threaded applications.

Would you like to dive deeper into any specific aspect of ArrayList or Vector?

Comments

Popular posts from this blog

Jenkins CICD in One Page

Why do we need a build tool?

Deutsche Bank Interview Questions - 2024