Stockez d'abord l'élément à fromIndex
dans une variable distincte item
et déplace les éléments voisins jusqu'à ce qu'il atteigne le toIndex
. Enfin, définissez le toIndex
à la item
.
public class ArrayListMove {
public static <E> void move(ArrayList<E> list, int fromIndex, int toIndex) {
if (fromIndex >= list.size() || fromIndex < 0)
throw new IndexOutOfBoundsException(outOfBoundsMsg(fromIndex, list.size()));
if (toIndex >= list.size() || toIndex < 0)
throw new IndexOutOfBoundsException(outOfBoundsMsg(toIndex, list.size()));
if (fromIndex == toIndex) return;
int from = fromIndex;
E item;
if (fromIndex < toIndex) {
item = list.set(from, list.get(from + 1));
from++;
while (from < toIndex) {
list.set(from, list.get(from + 1));
from++;
}
} else {
item = list.set(from, list.get(from - 1));
from--;
while (from > toIndex) {
list.set(from, list.get(from - 1));
from--;
}
}
list.set(toIndex, item);
}
private static String outOfBoundsMsg(int index, int size) {
return String.format(Locale.getDefault(), "Index: %d, Size: %d", index, size);
}
}
Si vous utilisez kotlin, utilisez les fonctions d'extension.
fun <E> ArrayList<E>.move(fromIndex: Int, toIndex: Int) {
if (fromIndex >= size || fromIndex < 0)
throw IndexOutOfBoundsException(outOfBoundsMsg(fromIndex, size))
if (toIndex >= size || toIndex < 0)
throw IndexOutOfBoundsException(outOfBoundsMsg(toIndex, size))
if (fromIndex == toIndex) return
if (fromIndex < toIndex) {
var from = fromIndex
val item = set(from, get(from + 1))
from++
while (from < toIndex) {
set(from, get(from + 1))
from++
}
set(toIndex, item)
} else {
var from = fromIndex
val item = set(from, get(from - 1))
from--
while (from > toIndex) {
set(from, get(from - 1))
from--
}
set(toIndex, item)
}
}
private fun outOfBoundsMsg(index: Int, size: Int): String {
return "Index: $index, Size: $size"
}