Notice: Function _load_textdomain_just_in_time was called incorrectly. Translation loading for the responsive-lightbox domain was triggered too early. This is usually an indicator for some code in the plugin or theme running too early. Translations should be loaded at the init action or later. Please see Debugging in WordPress for more information. (This message was added in version 6.7.0.) in /var/www/wp-includes/functions.php on line 6114

Notice: Function _load_textdomain_just_in_time was called incorrectly. Translation loading for the hueman domain was triggered too early. This is usually an indicator for some code in the plugin or theme running too early. Translations should be loaded at the init action or later. Please see Debugging in WordPress for more information. (This message was added in version 6.7.0.) in /var/www/wp-includes/functions.php on line 6114
Swap two elements in arrayList - Testingpool

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...