- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Replace all the elements of a Vector with Collections.fill() in Java
All the elements of a vector can be replaced by a specific element using java.util.Collections.fill() method. This method requires two parameters i.e. the Vector and the element that replaces all the elements in the Vector. No value is returned by the Collections.fill() method.
A program that demonstrates this is given as follows:
Example
import java.util.Collections; import java.util.Vector; public class Demo { public static void main(String args[]) { Vector vec = new Vector(5); vec.add(7); vec.add(4); vec.add(1); vec.add(2); vec.add(9); System.out.println("The Vector elements are: " + vec); Collections.fill(vec, 3); System.out.println("The Vector elements are: " + vec); } }
The output of the above program is as follows:
The Vector elements are: [7, 4, 1, 2, 9] The Vector elements are: [3, 3, 3, 3, 3]
Now let us understand the above program.
The Vector is created. Then Vector.add() is used to add the elements to the Vector. Collections.fill() method is used to replace all the elements of the Vector with element 3.
Then the Vector is displayed. A code snippet which demonstrates this is as follows:
Vector vec = new Vector(5); vec.add(7); vec.add(4); vec.add(1); vec.add(2); vec.add(9); System.out.println("The Vector elements are: " + vec); Collections.fill(vec, 3); System.out.println("The Vector elements are: " + vec);
Advertisements