- 概述
Java为我们提供了多种在_ArrayList_中重新排列元素的方法。在本教程中,我们将探讨其中的三种。
- 移动一个元素
最手动的方法,也是给我们最大控制权的方法,是直接将一个元素移动到新的位置。我们可以通过首先使用_ArrayList.remove()_来实现这一点,它返回被移除的元素。然后,我们可以选择性地使用_ArrayList.add()_将该元素重新插入到我们选择的位置:
@Test
void givenAList_whenManuallyReordering_thenOneItemMovesPosition() {
ArrayList````````<String>```````` arrayList = new ArrayList<>(Arrays.asList("one", "two", "three", "four", "five"));
String removed = arrayList.remove(3);
arrayList.add(2, removed);
ArrayList````````<String>```````` expectedResult = new ArrayList<>(Arrays.asList("one", "two", "four", "three", "five"));
assertEquals(expectedResult, arrayList);
}
大约 2 分钟