How to swap two elements by index in a list with Java

1 Answer

0 votes
import java.util.ArrayList;
import java.util.List;
import java.util.Collections;

public class MyClass {
    public static void main(String args[]) {
            List<String> lst = new ArrayList<String>();
 
            lst.add("Java");
            lst.add("C++");
            lst.add("Python");
            lst.add("C");
            lst.add("PHP");
            lst.add("C#");
 
            System.out.println(lst);
            
            Collections.swap(lst, 1, 4);
            
            System.out.println(lst);
    }
}



/*
run:

[Java, C++, Python, C, PHP, C#]
[Java, PHP, Python, C, C++, C#]

*/

 



answered Nov 6, 2022 by avibootz

Related questions

1 answer 164 views
2 answers 173 views
2 answers 179 views
3 answers 237 views
1 answer 149 views
1 answer 274 views
1 answer 167 views
...