Open Dhanrajpatil123 opened 3 days ago
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Vector;
public class VariableDataTypeEx {
public static void main(String[] args) {
Vector<Integer> vector1 = new Vector<>();
System.out.println(vector1.capacity());
Vector<Integer> vector2 = new Vector<>(15); // custom initial capacity
System.out.println(vector2.capacity());
Vector<Integer> vector3 = new Vector<>(5, 3); // custom capacity increment
System.out.println(vector3.capacity());
vector3.add(10);
vector3.add(10);
vector3.add(10);
vector3.add(10);
vector3.add(10);
System.out.println(vector3.capacity());
vector3.add(10);
System.out.println(vector3.capacity());
// 1
Vector<Integer> vector = new Vector<>(Arrays.asList(1, 2, 3, 4, 5));
// 2
LinkedList<Integer> list = new LinkedList<>();
list.add(1);
list.add(1);
list.add(1);
Vector<Integer> vector4 = new Vector<>(list);
System.out.println(vector4);
}
}
public static void main(String[] args) {
Vector<Integer> vector = new Vector<>(5, 3);
vector.add(10);
vector.add(20);
vector.add(30);
vector.add(40);
vector.add(50);
vector.add(1, 200); // 10, 20, 10, 10, 10, 10
for (int i = 0; i < vector.size(); i++) {
System.out.println(vector.get(i));
}
System.out.println(vector.get(1)); // 200
vector.set(2, 30); // 10, 200, 30, 30, 40, 50
vector.remove(1); // 10, 30, 30, 40, 50
vector.remove(vector.get(3)); // 10, 30, 30, 50
System.out.println(vector);
System.out.println(vector.contains(10)); // true
System.out.println(vector.contains(100)); // false
System.out.println(vector.isEmpty()); // false
vector.clear();
System.out.println(vector.isEmpty()); // true
}
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
Thread t1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
list.add(i);
}
});
Thread t2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
list.add(i);
}
});
t1.start();
t2.start();
try{
t1.join();
t2.join();
}
catch (InterruptedException e){
}
System.out.println(list.size()); // size can be any thing as per the elements can store
}
public static void main(String[] args) {
Vector<Integer> list = new Vector<>();
Thread t1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
list.add(i);
}
});
Thread t2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
list.add(i);
}
});
t1.start();
t2.start();
try{
t1.join();
t2.join();
}
catch (InterruptedException e){
}
System.out.println(list.size()); // size - > 2000
}
Vector
However, due it's synchronization overhead, it's generally recommended to use other modern alternatives like ArrayList in single-threaded scenarios. Despite this, Vector is still useful in certain situations, particularly in multi-threaded environments where thread safety is a concern.
Key Features of Vector
Constructor Of Vector