How to Swap Positions of Elements Specified in a Vector in Java


In this example, we may learn how to swap elements of java Vector object at specified index with swap method of Collections class.

Source Code

package com.beginner.examples;

import java.util.Collections;
import java.util.Vector;

public class SwapElementsVector {

	public static void main(String[] args) {

		Vector v = new Vector();

		v.add("a");
		v.add("b");
		v.add("c");
		v.add("d");

		// Use the swap() method of the Collections utility class
		// The second and third arguments are the positions of the elements that
		// need to be swapped.
		Collections.swap(v, 0, 3);

		System.out.println("v:" + v);
	}

}

Output:

v:[d, b, c, a]

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments