
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Swap Elements of ArrayList with Java Collections
In order to swap elements of ArrayList with Java collections, we need to use the Collections.swap() method. It swaps the elements at the specified positions in the list.
Declaration −The java.util.Collections.swap() method is declared as follows −
public static void swap(List <?> list, int i, int j)
where i is the index of the first element to be swapped, j is the index of the other element to be swapped and list is the list where the swapping takes place.
Let us see a program to swap elements of ArrayList with Java collections −
Example
import java.util.*; public class Example { public static void main (String[] args) { ArrayList<Integer> list = new ArrayList<Integer>(); list.add(10); list.add(20); list.add(30); list.add(40); list.add(50); System.out.println("Original list : " + list); Collections.swap(list, 3, 1); // swapping element at index 3 i.e. 40 and index 1 i.e. 20 System.out.println("List after swapping : " + list); } }
Output
Original list : [10, 20, 30, 40, 50] List after swapping : [10, 40, 30, 20, 50]
Advertisements