Java Swap two elements with swap()

Java Swap two elements with swap()


The Collections method swap() is very useful to swap two values in a programming code. For example, the prices of two different dates can be swapped. This method comes into existence with JDK 1.4.

Following is the method signature of swap() method

  • static void swap(List list1, int index1, int index2): List list1 elements at index numbers index1 and index2 are swapped.

If the index1 and index2 are same, three will be no affect. If the elements with index numbers of index1 and index2 do not exist, the method throws ArrayIndexOutOfBoundsException.

Example on Java Swap two elements with swap()


Java Swap two elements with swap()
Output screenshot of Java Swap two elements with swap()

ArrayList myList = new ArrayList();
myList.add(50);

An ArrayList object myList is created and added some elements with add() method inherited from List interface.

Collections.swap(myList, 0,1);
Collections.swap(myList, 2,3);

The elements of myList with index numbers 0 and 1 and also 2 and 3 are swapped. They are swapped in the original list itself.

Leave a Reply

Your email address will not be published. Required fields are marked *