Java Examples - Vector Swap

Advertisements


Problem Description:

How to swap two elements in a vector ?

Solution:

Following example .

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

public class Main {
   public static void main(String[] args) {
      Vector<String> v = new Vector();
      v.add("1");
      v.add("2");
      v.add("3");
      v.add("4");
      v.add("5");
      System.out.println(v);
      Collections.swap(v, 0, 4);
      System.out.println("After swapping");
      System.out.println(v);
   }
}

Result:

The above code sample will produce the following result.

1 2 3 4 5 
After swapping
5 2 3 4 1


Advertisements
Advertisements