A
A
Alexander2014-05-04 13:39:23
Java
Alexander, 2014-05-04 13:39:23

How to move an array element to a different index in Java?

For example, there is an array:
List<RowItem> data = new ArrayList<RowItem>();
With 5 elements

data.add(new RowItem("Элемент: 0"));
data.add(new RowItem("Элемент: 1"));
data.add(new RowItem("Элемент: 2"));
data.add(new RowItem("Элемент: 3"));
data.add(new RowItem("Элемент: 4"));

You need to move - "Item: 3" to the second position to get:
"Item: 0"
"Item: 3"
"Item: 1"
"Item: 2"
"Item: 4"
I tried to delete and add by index,
RowItem item = data.get(3); // Получаю объект "Элемент: 3" 
data.remove(3);
data.add(1, item);

but after deletion the object disappeared and the link became null.
I also did it using the set method, but it swaps positions, and I need it to be added to the second position, and "Element: 1" moved to index 2.
RowItem row = data.get(indexOne);
data.set(indexOne, data.get(indexTwo));
data.set(indexTwo, row);

absolutely the same as:
Collections.swap(data, 1, 3);
How to properly move objects in an array?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander, 2014-05-04
@UserAlexandr

RowItem item = data.remove(3);
data.add(1, item);

O
Ololesha Ololoev, 2014-05-04
@alexeygrigorev

Collections.swap(data, 3, 2)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question