How to swap two items in ArrayList in Java

The following code swaps; two elements in an ArrayList. You can swap two items by calling the Collections.swap(int i1, int i2) . You must pass as arguments the indices of the two objects to be swapped.

import java.util.ArrayList; 
import java.util.Collections;

public class swap {

public static void main(String a[]){
ArrayList arlist = new ArrayList();

arlist.add("o1");
arlist.add("o2");
arlist.add("o3");
arlist.add("o4");

System.out.println("Before: "+arlist);

//swap the two objects at index 1 and 3
//o2 and o4
Collections.swap(arlist, 1, 3);

System.out.println("After: "+arlist);

}
}
Result:

Before: [o1, o2, o3, o4]
After: [o1, o4, o3, o2]
Reference:
javadoc: Collections.swap()

Commentaires (12)

Connectez-vous pour commenter

Rejoignez la discussion et partagez vos connaissances avec la communauté

JD
Jean Dupont Il y a 2 heures

Excellent tutoriel !

👍 12 Répondre Signaler
CodeurJava ✓ Auteur • Il y a 1 heure

N'hésitez pas si vous avez des questions.