Java Vector
Vector is like the dynamic array which can grow or shrink its size. Unlike
array, we can store n-number of elements in it as there is no size limit. It
is a part of Java Collection framework since Java 1.2. It is found in
the [Link] package.
Java Vector Example
1. import [Link].*;
2. public class VectorExample {
3. public static void main(String args[]) {
4. //Create a vector
5. Vector<String> vec = new Vector<String>();
6. //Adding elements using add() method of List
7. [Link]("Tiger");
8. [Link]("Lion");
9. [Link]("Dog");
10. [Link]("Elephant");
11. //Adding elements using addElement() method of Vector
12. [Link]("Rat");
13. [Link]("Cat");
14. [Link]("Deer");
15.
16. [Link]("Elements are: "+vec);
17. }
18. }
Output:
Elements are: [Tiger, Lion, Dog, Elephant, Rat, Cat, Deer]
Java Vector Example 2
1. import [Link].*;
2. public class VectorExample1 {
3. public static void main(String args[]) {
4. //Create an empty vector with initial capacity 4
5. Vector<String> vec = new Vector<String>(4);
6. //Adding elements to a vector
7. [Link]("Tiger");
8. [Link]("Lion");
9. [Link]("Dog");
10. [Link]("Elephant");
11. //Check size and capacity
12. [Link]("Size is: "+[Link]());
13. [Link]("Default capacity is: "+[Link]());
14. //Display Vector elements
15. [Link]("Vector element is: "+vec);
16. [Link]("Rat");
17. [Link]("Cat");
18. [Link]("Deer");
19. //Again check size and capacity after two insertions
20. [Link]("Size after addition: "+[Link]());
21. [Link]("Capacity after addition is: "+[Link]());
22. //Display Vector elements again
23. [Link]("Elements are: "+vec);
24. //Checking if Tiger is present or not in this vector
25. if([Link]("Tiger"))
26. {
27. [Link]("Tiger is present at the index " +[Link]("Tig
er"));
28. }
29. else
30. {
31. [Link]("Tiger is not present in the list.");
32. }
33. //Get the first element
34. [Link]("The first animal of the vector is = "+[Link]
ent());
35. //Get the last element
36. [Link]("The last animal of the vector is = "+[Link]
ent());
37. }
38. }
Output:
Size is: 4
Default capacity is: 4
Vector element is: [Tiger, Lion, Dog, Elephant]
Size after addition: 7
Capacity after addition is: 8
Elements are: [Tiger, Lion, Dog, Elephant, Rat, Cat, Deer]
Tiger is present at the index 0
The first animal of the vector is = Tiger
The last animal of the vector is = Deer