-1

Lets say I have an ArrayList name list

Item 1
Item 2
Item 3
Item 4
Item 5
Item 6

How would I do this: Move Item 2 to index 3

Item 1
Item 3
Item 4
Item 2
Item 5
Item 6
Hobbs2000
  • 311
  • 1
  • 6
  • 19

2 Answers2

2

You can use Collections.swap if you know the index of elements you wish to swap

Collections.swap(list,i,j);

And you can get the index of an element using list.indexOf(element) if you don't know the index

Sleiman Jneidi
  • 22,907
  • 14
  • 56
  • 77
0

You can set the item to any position in the list using set method, however, it would overwrite the existing item, to perform a swap, we can do the following:

List<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
System.out.println(list);
String element0 = list.get(0);
String element1 = list.get(1);
list.set(0, element1);
list.set(1, element0);
System.out.println(list);
Darshan Mehta
  • 30,102
  • 11
  • 68
  • 102