Swap two elements in arrayList

In the previous post, we have seen how to compare two arrayLists. In this post, we will see how to swap two elements in arrayList.

We have a method called Collections.swap()  which is used to swap the elements in the arrayList.

Syntax:

public static void swap(List list, int i1, int i2)

list: A arrayList

i1: First item to be swapped

i2: Second item to be swapped with first item

It throws IndexOutOfBoundsException – if either i1 or i2 is less than zero or greater than the size of the list (i1 < 0 || i1 >= list.size() || i2 < 0 || i2 >= list.size()).

Example:

Output:

Fruits list before Swap
Orange
Mango
Apple
Grapes
Banana
Date
Papaya
Fruits list after Swap
Orange
Mango
Date
Grapes
Banana
Apple
Papaya


Questions/Suggestions
Have any question or suggestion for us?Please feel free to post in Q&A Forum
Print Friendly, PDF & Email
Compare two arrayLists in java
Replace the value of existing element in ArrayList
Shekhar Sharma

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. He is an automation engineer having more than 8 years of experience who loves troubleshooting in automation and finding innovative ways to solve the problems. His other leisurely activities includes playing harmonica, paintings, sketching portrait, watching movies and travelling etc.

You may also like...

Leave a Reply

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