- 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
Add elements at the middle of a Vector in Java
Elements can be added in the middle of a Vector by using the java.util.Vector.insertElementAt() method. This method has two parameters i.e. the element that is to be inserted in the Vector and the index at which it is to be inserted. If there is an element already present at the index specified by Vector.insertElementAt() then that element and all subsequent elements shift to the right by one.
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(5); for (int i = 0; i < 5; i++) { vec.insertElementAt(i + 1, i); } System.out.println("The Vector elements are: " + vec); vec.insertElementAt(9, 1); System.out.println("The Vector elements are: " + vec); } }
The output of the above program is as follows −
The Vector elements are: [1, 2, 3, 4, 5] The Vector elements are: [1, 9, 2, 3, 4, 5]
Now let us understand the above program.
The Vector is created. Then Vector.insertElementAt() is used to add the elements to the Vector at the specified index. Finally, the Vector elements are displayed. A code snippet which demonstrates this is as follows −
Vector vec = new Vector(5); for (int i = 0; i < 5; i++) { vec.insertElementAt(i+1, i); } System.out.println("The Vector elements are: " + vec); vec.insertElementAt(9, 1); System.out.println("The Vector elements are: " + vec);
- Related Articles
- Add elements at the end of a Vector in Java
- Add elements to a Vector in Java
- Add elements at beginning and end of LinkedList in Java
- Adding elements in the middle of an ArrayList in Java
- Replace all the elements of a Vector with Collections.fill() in Java
- Clear out all of the Vector elements in Java
- Enumerate through the Vector elements in Java
- Removing Single Elements in a Vector in Java
- Loop through the Vector elements using a ListIterator in Java
- Replace an element at a specified index of the Vector in Java
- How to add elements to AbstractSequentialList class at a specific position in Java?
- Append all elements of another Collection to a Vector in Java
- Which type of lenses are:(a) thinner in the middle than at the edges?(b) thicker in the middle than at the edges?
- Middle of three elements - JavaScript
- Loop through the Vector elements using an Iterator in Java
