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:

public class ArrayListEx {

	public static void main(String[] args) {
		ArrayList<String> fruits1 = new ArrayList<String>();
		fruits1.add("Orange");
		fruits1.add("Mango");
		fruits1.add("Apple");
		fruits1.add("Grapes");
		fruits1.add("Banana");
		fruits1.add("Date");
		fruits1.add("Papaya");
		
		System.out.println("Fruits list before Swap");
		for(String str : fruits1)
			System.out.println(str);
		
		//Swap  between index 2 and 5
		Collections.swap(fruits1, 2, 5);
		
		System.out.println("Fruits list after Swap");
		for(String str : fruits1)
			System.out.println(str);

	}
}

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
Avatar photo

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

You may also like...