Pratik
Pratik

Reputation: 79

Difference between void insertElementAt(Object obj, int index) and void set(int index,object o)

Are both methods alternative to each other or they have any specific role in while adding element in vector in the middle like performance wise?

Upvotes: 0

Views: 378

Answers (2)

Mureinik
Mureinik

Reputation: 311163

insertElementAt inserts the given element at the given index, and shifts all the elements after it. E.g., if you were to insert an element in index 2, the element that was at index 2 before the insertion would now be in index 3, the element at index 3 would now be in 4, etc.
set, on the other hand, just overwrites the element at the given index.

Consider the following snippet:

Vector<String> vec = new Vector<>(Arrays.asList("a", "b", "c", "d"));
System.out.println(vec);

vec.insertElementAt("e", 2);
System.out.println(vec);

vec.set(2, "f");
System.out.println(vec);

The call to insertElementAt inserts an "e" between the "b" and the "c". The call to set overwrites that "e" with an "f". I.e., the resulting output would be:

[a, b, c, d]
[a, b, e, c, d]
[a, b, f, c, d]

Upvotes: 2

O.O.Balance
O.O.Balance

Reputation: 3030

insertElementAt() will add the new element to the vector preserving the previous elements. set() will overwrite the element at the given index.

Vector<String> vector = new Vector<>();
vector.add("A"); // A
vector.add("B"); // A B
vector.insertElementAt("C", 1); // A C B
vector.set(1, "D"); // A D B

Upvotes: 1

Related Questions