Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
How to Swap Two Elements in a LinkedList in Java?
Next article icon

How to Swap Two Elements in an ArrayList in Java?

Last Updated : 01 Jul, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

We can swap two elements of Array List using Collections.swap() method. This method accepts three arguments. The first argument is the ArrayList and the other two arguments are the indices of the elements. This method returns nothing. 

Syntax:

public static void swap(List list, int a, int b);

Parameters

  • list: An ArrayList or any List implementing class in which elements are swapped
  • a: index of the first element
  • b: index of the second element

Exception: It throws IndexOutOfBoundsException if the index of Array List is less than 0 or greater than the size of the ArrayList.

Example 1

Java

// Java program to swap two elements in an ArrayList
 
import java.util.ArrayList;
import java.util.Collections;
 
public class GFG {
 
    public static void main(String a[])
    {
 
        // Create the Array List
        ArrayList<String> ArrList = new ArrayList<String>();
 
        // add the values in Array List
        ArrList.add("Item 1");
        ArrList.add("Item 2");
        ArrList.add("Item 3");
        ArrList.add("Item 4");
        ArrList.add("Item 5");
 
        // display Array List before swap
        System.out.println("Before Swap the ArrayList ");
        System.out.println(ArrList);
 
        // Swapping the elements at 1 and 2 indices
        Collections.swap(ArrList, 1, 2);
 
        // display Array List after swap
        System.out.println("After Swap the ArrayList");
        System.out.println(ArrList);
    }
}
                      
                       

 
 


Output
Before Swap the ArrayList  [Item 1, Item 2, Item 3, Item 4, Item 5] After Swap the ArrayList [Item 1, Item 3, Item 2, Item 4, Item 5]


 

Example 2


 

Java

// Java program to swap two elements in an ArrayList
 
import java.util.ArrayList;
import java.util.Collections;
 
public class GFG {
 
    public static void main(String a[]) throws Exception
    {
 
        // Create the Array List
        ArrayList<String> ArrList = new ArrayList<String>();
 
        // add the values in Array List
        ArrList.add("Item 1");
        ArrList.add("Item 2");
        ArrList.add("Item 3");
        ArrList.add("Item 4");
        ArrList.add("Item 5");
 
        // display Array List before swap
        System.out.println("Before Swap the ArrayList ");
        System.out.println(ArrList);
 
        // Swapping the elements at -1 and 2 indices
        // Throws IndexOutOfBounds Exception
        Collections.swap(ArrList, -1, 2);
    }
}
                      
                       

 

 

Output


 

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index -1 out of bounds for length 5     at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)     at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)     at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248)     at java.base/java.util.Objects.checkIndex(Objects.java:372)     at java.base/java.util.ArrayList.get(ArrayList.java:458)     at java.base/java.util.Collections.swap(Collections.java:501)     at GFG.main(GFG.java:27)


 



Next Article
How to Swap Two Elements in a LinkedList in Java?
author
mukulsomukesh
Improve
Article Tags :
  • Java
  • Java Programs
  • Java-ArrayList
Practice Tags :
  • Java

Similar Reads

  • How to Add Element in Java ArrayList?
    Java ArrayList class uses a dynamic array for storing the elements. It is like an array, but there is no size limit. We can add or remove elements anytime. So, it is much more flexible than the traditional array. Element can be added in Java ArrayList using add() method of java.util.ArrayList class.
    2 min read
  • How to Replace a Element in Java ArrayList?
    To replace an element in Java ArrayList, set() method of java.util. An ArrayList class can be used. The set() method takes two parameters the indexes of the element that has to be replaced and the new element. The index of an ArrayList is zero-based. So, to replace the first element, 0 should be the
    2 min read
  • How to Swap Two Elements in a LinkedList in Java?
    Given a Linked List, the task is to swap two elements without disturbing their links. There are multiple ways to swap. Elements can be swapped using by swapping the elements inside the nodes, and by swapping the complete nodes. Example: Input :- 10->11->12->13->14->15 element1 = 11 el
    4 min read
  • How to Add an Element at Particular Index in Java ArrayList?
    ArrayList.add() method is used to add an element at particular index in Java ArrayList. Syntax: public void add(int index, Object element) ; Parameters: index -position at which the element has to be inserted. The index is zero-based.element - the element to be inserted at the specified position. Ex
    2 min read
  • How to Shuffle the Elements of Array in Java?
    In Java, to shuffle the elements of an array, we can use the shuffle() method from the Collections class. This method is part of the java.util package. To shuffle an array, first, we need to convert the array into a List, shuffle it, and then convert it back to an array if needed. Example: Let's go
    3 min read
  • How to Copy and Add all List Elements to an Empty ArrayList in Java?
    We can copy and add List items in Array List using addAll() method. This method accepts a Collection (Ex. List) as an argument and adds the collection items at the end of its calling Collection (Ex. ArrayList). This method returns a boolean value. addAll() return true if the collection successfully
    2 min read
  • How to Convert TreeMap to an ArrayList in Java?
    TreeMap is a part of the Java Collection framework. Java TreeMap contains values based on the key. It implements the NavigableMap interface and extends AbstractMap class. It provides an efficient means of storing key-value pairs in sorted order. Java TreeMap contains only unique elements. It cannot
    4 min read
  • Removing last element from ArrayList in Java
    Given an ArrayList collection in Java, the task is to remove the last element from the ArrayList. Example: Input: ArrayList[] = [10, 20, 30, 1, 2] Output: [10, 20, 30, 1] After removing the last element 2, the ArrayList is: [10, 20, 30, 1] Input: ArrayList[] = [1, 1, 2, 2, 3] Output: [1, 1, 2, 2] Af
    2 min read
  • How to Declare an ArrayList with Values in Java?
    ArrayList is simply known as a resizable array. Declaring an ArrayList with values is a basic task that involves the initialization of a list with specific elements. It is said to be dynamic as the size of it can be changed. Proceeding with the declaration of ArrayList, we have to be aware of the co
    2 min read
  • How to Insert an element at a specific position in an Array in Java
    An array is a collection of items stored at contiguous memory locations. In this article, we will see how to insert an element in an array in Java.Given an array arr of size n, this article tells how to insert an element x in this array arr at a specific position pos. Approach 1: Here's how to do it
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences