Swap elements of Java ArrayList example

In this tutorials how to swap arraylist elements. We can swap arraylist element by using collections.swap() method and second we can write our own method.

  1. Swap arraylist element using collections.swap() method.
  2. Swap arraylist element by our own method.

1. Swap arraylist element using collections.swap() method

syntax

public static void swap(List<?> list, int i, int j) {

}
  • This method swaps the elements at the given positions in the specified list.
  • If the specified positions are equal, invoking this method leaves the list unchanged.
  • This method take list in which to swap elements , i the index of one element to be swapped and j the index of the other element to be swapped as paramater .
  • It throws IndexOutOfBoundsException – if either i or j is out of range (i < 0 || i >= list.size() || j < 0 || j >= list.size()).
import java.util.ArrayList;


import java.util.Collections;

public class SwapElement {

public static void main(String[] args) {
ArrayList<String> arr = new ArrayList<String>();
// add element in arraylist
arr.add("c");
arr.add("php");
arr.add("html");
arr.add("java");
// print arraylist
System.out.println("ArrayList Before Swap is = " + arr);

/*
* Swaps the elements at the specified positions in the specified list.


*/

Collections.swap(arr, 1, 3);

System.out.println("ArrayList Before Swap is = " + arr);

}

}

Output:

ArrayList Before Swap is = [c, php, html, java]

ArrayList Before Swap is = [c, java, html, php]

2. Swap arraylist element by our own method.

In this method we will use temporary variable for swap two element of arraylist

import java.util.ArrayList;

public class ArrayListSwap {
	public static void main(String[] args) {
		ArrayList<String> arr = new ArrayList<String>();
		// add element in arraylist
		arr.add("c");
		arr.add("php");
		arr.add("html");
		arr.add("java");
		// print arraylist
		System.out.println("ArrayList Before Swap is = " + arr);
		int i = 1 ;
		int j = 2;
		
		//assign  element from position i to temporary variable 
		String element = arr.get(i);
		//replace element on position i from position j
		arr.set(i, arr.get(j));
		//replace element on postion j from temporary variable
		arr.set(j, element);
		//print arraylist
		System.out.println("Arraylist after swap is ="+ arr);
		
		}	
	}

Output :

ArrayList Before Swap is = [c, php, html, java]
Arraylist after swap is =[c, html, php, java]

 

Leave a Reply

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

29 − = 22