beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
    • Learn jQuery
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

How to swap two elements in an ArrayList

By Chaitanya Singh | Filed Under: Java Collections

This tutorial will help you understand how to swap two elements in an ArrayList. We are using Collections.swap() method for swapping.

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

This method swaps the element of index i1 with the element of index i2. 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 of swapping two elements in ArrayList

In this example we have a ArrayList<String> and we are swapping 2nd (index =1) and 5th (index=4) element of ArrayList using Collections.swap() method.

package beginnersbook.com;
import java.util.ArrayList;
import java.util.Collections;

public class SwappingExample {

 public static void main(String a[]){
    ArrayList<String> al = new ArrayList<String>();
    al.add("Sachin");
    al.add("Rahul");
    al.add("Saurav");
    al.add("Sunil");
    al.add("Kapil");
    al.add("Vinod");

    System.out.println("ArrayList before Swap:");
    for(String temp: al){
        System.out.println(temp);
    }

    //Swapping 2nd(index 1) element with the 5th(index 4) element
    Collections.swap(al, 1, 4);

    System.out.println("ArrayList after swap:");
    for(String temp: al){
       System.out.println(temp);
    }
  }
}

Output:

ArrayList before Swap:
Sachin
Rahul
Saurav
Sunil
Kapil
Vinod
ArrayList after swap:
Sachin
Kapil
Saurav
Sunil
Rahul
Vinod

Leave a Reply Cancel reply

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

Java Tutorial

  • Java Tutorial
  • OOPs Concepts

Java Collections

  • ArrayList
  • LinkedList
  • ArrayList vs LinkedList
  • Vector
  • ArrayList vs Vector
  • HashMap
  • TreeMap
  • LinkedHashMap
  • HashSet
  • TreeSet
  • LinkedHashSet
  • Hashtable
  • HashMap vs Hashtable
  • Queue
  • PriorityQueue
  • Deque & ArrayDeque
  • Iterator
  • ListIterator
  • Comparable Interface
  • Comparator Interface
  • Java Collections Interview Q

MORE ...

  • Java String
  • Exception handling
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations

Copyright © 2012 – 2022 BeginnersBook . Privacy Policy . Sitemap