Vector in java is a part of Java’s collections framework. Vector is a dynamic array of objects, i.e., the size of the vector can be modified as per the requirement. Vector implements the List interface. It also maintains the insertion order and the elements of the vector can be accessed using their indexes. The vector in java is synchronized.
We can access the vector elements in the following ways:
- Using their indexes
- By using the iterator
- By randomly calling the elements from the vector
Different ways to get random elements from the vector:
- Using random() method of Math class
- Using Random class
- Using ThreadLocalRandom class
Method 1: Using random() method of Math class
The Math class of the java.lang package has a method random() which returns a positive double value which is greater than 0.0 and less than 1.0. We can use this method to generate a random index and access the element present at that index in the given vector.
For To Welcome Welcome Geeks
Method 2: Using Random class
To generate the random index we can also use the Random class of the java.util package. It provides useful methods to generate random numbers of the specified type and within specified ranges.
Welcome Geeks To Geeks For
Method 3: Using ThreadLocalRandom class
ThreadLocalRandom class of the java.util.concurrent is a random number generator isolated to the current thread. It generates a random number of a specified type and within the specified range for each thread in a multi-threading environment. We can generate the random index using the nextInt() method of this class and access the element at that index from the given vector.
Geeks Welcome Geeks To To
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.