0% found this document useful (0 votes)
12 views

6.1 Differences Between Vectors and Arrays in Java

Vectord and arrays in java

Uploaded by

chaitanyadogga0
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

6.1 Differences Between Vectors and Arrays in Java

Vectord and arrays in java

Uploaded by

chaitanyadogga0
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

Differences Between Vectors and Arrays in

Java
In the world of Java programming, data structures play a crucial role in
storing and manipulating data efficiently. Two commonly used data
structures for this purpose are vectors and arrays. While both are used to
store collections of elements, they have distinct differences that make
them suitable for different scenarios. In this section, we will explore the
dissimilarities between vectors and arrays in Java.

Java Array
An array in Java is a fixed-size, homogeneous data structure that stores
elements of the same type. Arrays have a static length, meaning the size
is determined at the time of declaration and cannot be changed during
runtime.

They offer direct access to elements using an index, which makes array
operations fast and efficient.

File Name: ArrayExample.java

1. public class ArrayExample {


2. public static void main(String[] args) {
3. // Declaration and initialization of an array
4. int[] intArray = new int[3];
5. // Assigning values to array elements
6. intArray[0] = 1;
7. intArray[1] = 2;
8. intArray[2] = 3;
9. // Accessing array elements
10. for (int i = 0; i < intArray.length; i++) {
11. System.out.println("Element at index " + i + ": " + intA
rray[i]);
12. }
13. }
14. }

Output:

Element at index 0: 1
Element at index 1: 2
Element at index 2: 3

Java Vector
A vector is a dynamic and resizable array-like data structure that belongs
to the Java Collections Framework. Vectors can grow or shrink in size
dynamically, allowing for flexibility in managing the number of elements
they contain.

Vectors are part of the java.util package and implement the List interface,
providing various methods for manipulation. Let's go through some simple
examples for both arrays and vectors in Java to illustrate their differences.

File Name: VectorExample.java

1. import java.util.Vector;
2. public class VectorExample {
3. public static void main(String[] args) {
4. // Declaration and initialization of a Vector
5. Vector<Integer> integerVector = new Vector<>();
6. // Adding elements to the Vector
7. integerVector.add(1);
8. integerVector.add(2);
9. integerVector.add(3);
10. // Accessing vector elements
11. for (int i = 0; i < integerVector.size(); i++) {
12. System.out.println("Element at index " + i + ": " + inte
gerVector.get(i));
13. }
14. }
15. }

Output:

Element at index 0: 1
Element at index 1: 2
Element at index 2: 3

Comparison of Programs
In the array example, we declare and initialize an array with a fixed size.
We then assign values to its elements and access them using indices.

ADVERTISEMENT
In the vector example, we have used the Vector class from the java.util
package. Vectors are dynamic and can grow or shrink as needed. We add
elements using the add() method and access them using the get()
method.

Both examples output the elements present in the array or vector,


demonstrating the basic operations associated with each data structure.

Size Flexibility
Array
Once an array is created, its size remains constant, and we cannot change
it dynamically. To resize an array, we need to create a new array and copy
the elements from the old array to the new one.

Arrays in Java (Fixed Size):

File Name: ArrayExample.java

1. public class ArrayExample {


2. public static void main(String[] args) {
3. // Declaration and initialization of an array with a fixed size
4. int[] intArray = new int[3];
5. // Assigning values to array elements
6. intArray[0] = 1;
7. intArray[1] = 2;
8. intArray[2] = 3;
9. // Attempting to resize the array (not possible)
10. // This will result in compilation error
11. intArray[3] = 4;// commenting this line will not result in a
n error
12. // Accessing array elements
13. for (int i = 0; i < intArray.length; i++) {
14. System.out.println("Element at index " + i + ": " + intA
rray[i]);
15. }
16. }
17. }

Output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index
3 out of bounds for length 3
at ArrayResizeErrorExample.main(ArrayResizeErrorExample.java:12)

In the above example, attempting to resize the array by creating a new


array with a different size will result in a compilation error.

The following program overcome the compilation error.

File Name: ArrayExample.java

1. public class ArrayExample {


2. public static void main(String[] args) {
3. // Declaration and initialization of an array with a fixed size
4. int[] intArray = new int[3];
5. // Assigning values to array elements
6. intArray[0] = 1;
7. intArray[1] = 2;
8. intArray[2] = 3;
9. // Attempting to resize the array (not possible)
10. // This will result in creating a new array and copying ele
ments
11. int[] newArray = new int[5];
12. System.arraycopy(intArray, 0, newArray, 0, intArray.lengt
h);
13. intArray = newArray;
14. // Assigning new values to additional elements
15. intArray[3] = 4;
16. intArray[4] = 5;
17. // Accessing array elements
18. for (int i = 0; i < intArray.length; i++) {
19. System.out.println("Element at index " + i + ": " + intA
rray[i]);
20. }
21. }
22. }

Output:

Element at index 0: 1
Element at index 1: 2
Element at index 2: 3
Element at index 3: 4
Element at index 4: 5

Vector
Vectors are dynamic and can be resized during runtime using methods
like add() and remove(). The Vector class automatically handles the
resizing of the underlying array, providing a convenient way to manage
the size of the collection.

Let's create examples to demonstrate the size flexibility of arrays and


vectors in Java.

Vectors in Java (Resizable):

File Name: VectorExample.java

1. import java.util.Vector;
2. public class VectorExample {
3. public static void main(String[] args) {
4. // Declaration and initialization of a Vector
5. Vector<Integer> integerVector = new Vector<>();
6. // Adding elements to the Vector
7. integerVector.add(1);
8. integerVector.add(2);
9. integerVector.add(3);
10. // Resizing the Vector dynamically
11. integerVector.add(4);
12. integerVector.add(5);
13. // Accessing vector elements
14. for (int i = 0; i < integerVector.size(); i++) {
15. System.out.println("Element at index " + i + ": " + inte
gerVector.get(i));
16. }
17. }
18. }

Output:

Element at index 0: 1
Element at index 1: 2
Element at index 2: 3
Element at index 3: 4
Element at index 4: 5
In this example, the Vector is dynamically resized by adding two more
elements to it after the initial elements have been added. Vectors can
grow or shrink in size during runtime, providing flexibility in managing the
number of elements they contain.

Synchronization
Array
Arrays in Java are not synchronized, meaning they are not thread-safe. If
multiple threads are accessing or modifying an array concurrently, we
may encounter data inconsistencies.

Arrays in Java (Not Synchronized):

File Name: ArrayThreadExample.java

1. public class ArrayThreadExample {


2. public static void main(String[] args) {
3. // Declaration and initialization of an array
4. int[] intArray = new int[3];
5. // Creating two threads that modify the array concurrently
6. Thread thread1 = new Thread(() -> {
7. for (int i = 0; i < intArray.length; i++) {
8. intArray[i]++;
9. }
10. });
11. Thread thread2 = new Thread(() -> {
12. for (int i = 0; i < intArray.length; i++) {
13. intArray[i]--;
14. }
15. });
16. // Start the threads
17. thread1.start();
18. thread2.start();
19. try {
20. // Wait for threads to complete
21. thread1.join();
22. thread2.join();
23. } catch (InterruptedException e) {
24. e.printStackTrace();
25. }
26. // Accessing array elements after concurrent modification

27. for (int i = 0; i < intArray.length; i++) {


28. System.out.println("Element at index " + i + ": " + intA
rray[i]);
29. }
30. }
31. }

Output:

Element at index 0: 0
Element at index 1: 0
Element at index 2: 0

In this example, two threads concurrently modify the array without any
synchronization. As a result, data inconsistencies may occur, and the final
values of the array elements can vary.

Vector
Vectors are synchronized by default, ensuring that multiple threads can
safely access and modify them. While synchronization introduces
overhead, it can be beneficial in situations where thread safety is a
concern.

Let's create examples to demonstrate the synchronization differences


between arrays and vectors in a multithreaded scenario.

Vectors in Java (Synchronized):

File Name: VectorThreadExample.java

1. import java.util.Vector;
2. public class VectorThreadExample {
3. public static void main(String[] args) {
4. // Declaration and initialization of a Vector
5. Vector<Integer> integerVector = new Vector<>();
6. // Creating two threads that modify the vector concurrently
7. Thread thread1 = new Thread(() -> {
8. for (int i = 0; i < 3; i++) {
9. integerVector.add(i);
10. }
11. });
12. Thread thread2 = new Thread(() -> {
13. for (int i = 0; i < 3; i++) {
14. integerVector.remove(0);
15. }
16. });
17. // Start the threads
18. thread1.start();
19. thread2.start();
20. try {
21. // Wait for threads to complete
22. thread1.join();
23. thread2.join();
24. } catch (InterruptedException e) {
25. e.printStackTrace();
26. }
27. // Accessing vector elements after concurrent modificatio
n
28. for (int i = 0; i < integerVector.size(); i++) {
29. System.out.println("Element at index " + i + ": " + inte
gerVector.get(i));
30. }
31. }
32. }

Output:

Element at index 0: 2
Element at index 1: 1

In this example, the Vector class automatically handles synchronization.


As a result, even when multiple threads are modifying the vector
concurrently, the data remains consistent, ensuring thread safety.

Performance

You might also like