Javatpoint Logo
Javatpoint Logo

Java Collections swap() Method

The swap() method of Java Collections class is used to swap the elements at the specified positions in the specified list.

Syntax

Following is the declaration of swap() method:

Parameter

Parameter Description Required/Optional
list It is the list in which we will swap the elements. Required
i It is the index of one element to be swapped. Required
j It is the index of the other element to be swapped. Required

Returns

The swap() method does not return anything.

Exceptions

IndexOutOfBoundsException- It will thrown this exception if the i or j is out of range.

Compatibility Version

Java 1.4 and above

Example 1

Test it Now

Output:

Original List : [Java, Android, Python, Node.js]
List after swapping : [Python, Android, Java, Node.js]

Example 2

Test it Now

Output:

List before swapping: [44, 55, 99, 77, 88, 66]
List after swapping: [44, 55, 66, 77, 88, 99]

Example 3

Test it Now

Output:

List before swapping: [44, 55, 99, 77, 88, 66, 33, 22]
Enter index i : 2
Enter index j : 7
List after swapping: [44, 55, 22, 77, 88, 66, 33, 99]





Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA