- 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
Set the size of a Vector in Java
The java.util.Vector.setSize() method can be used to set the size of a Vector in Java. If the new size that is set is greater than the old size of the Vector, then null values are added to the positions created. If the new size that is set is lesser than the old size of the Vector, then the elements at positions more than the new size are discarded.
A program that demonstrates this is given as follows:
Example
import java.util.Vector; public class Demo { public static void main(String args[]) { Vector vec = new Vector(); vec.add(4); vec.add(1); vec.add(7); vec.add(3); vec.add(5); vec.add(9); vec.add(2); vec.add(8); vec.add(6); System.out.println("The Vector elements are: " + vec); vec.setSize(5); System.out.println("The Vector elements are: " + vec); } }
The output of the above program is as follows:
The Vector elements are: [4, 1, 7, 3, 5, 9, 2, 8, 6] The Vector elements are: [4, 1, 7, 3, 5]
Now let us understand the above program.
The Vector is created. Then Vector.add() is used to add the elements to the Vector. The Vector is displayed. A code snippet which demonstrates this is as follows:
Vector vec = new Vector(); vec.add(4); vec.add(1); vec.add(7); vec.add(3); vec.add(5); vec.add(9); vec.add(2); vec.add(8); vec.add(6); System.out.println("The Vector elements are: " + vec);
The Vector.setSize() method is used to set the size of the Vector to 5. The Vector is displayed again with only 5 elements as the rest of the elements are discarded. A code snippet which demonstrates this is as follows:
vec.setSize(5); System.out.println("The Vector elements are: " + vec);
- Related Articles
- What is the difference between size and capacity of a Vector in Java?
- How do I set the size of a list in Java?
- How to set minimum size limit for a JFrame in Java
- Set the size of the icons in HTML
- Find the maximum element of a Vector in Java
- Find the minimum element of a Vector in Java
- Role of size property in CSS to set the size and orientation of a page box
- Find the size of a HashMap in Java
- Add elements at the middle of a Vector in Java
- Add elements at the end of a Vector in Java
- How to set preferred Size for BoxLayout Manager in Java?
- 2D vector in C++ with user defined size
- How to find the unique combinations of a string vector elements with a fixed size in R?
- Replace all the elements of a Vector with Collections.fill() in Java
- How to create a large vector with repetitive elements of varying size in R?
