如何使用Java将一组对象移动到ArrayList中的不同位置?
假设我有一个ArrayList,它的值为{1,4,6,54,9,34,21,53} 我需要将值1、4和6移动到34之后的索引中。我还需要将值21和53移到54前面。所以我的数组列表应该像{21,53,54,9,34,1,4,6} 我尝试使用: 集合。旋转(arr.subList(0,2),-3); 集合。旋转(arr.subList(6,7,2) 但是,所有这些都只是在子列表中旋转索引 你有什么想法可以让它工作吗 我注意到如何使用Java将一组对象移动到ArrayList中的不同位置?,java,collections,arraylist,sublist,Java,Collections,Arraylist,Sublist,假设我有一个ArrayList,它的值为{1,4,6,54,9,34,21,53} 我需要将值1、4和6移动到34之后的索引中。我还需要将值21和53移到54前面。所以我的数组列表应该像{21,53,54,9,34,1,4,6} 我尝试使用: 集合。旋转(arr.subList(0,2),-3); 集合。旋转(arr.subList(6,7,2) 但是,所有这些都只是在子列表中旋转索引 你有什么想法可以让它工作吗 我注意到 Collections.rotate(arr.subList(0, 6)
Collections.rotate(arr.subList(0, 6), -3);
根据需要将1、4和6移动到34之后的索引。我怀疑这个技巧通常是适用的,这取决于目标索引是在移动子列表之前还是之后
<T> void moveTo(List<T> list, int fromIndex, int toIndex, int destIndex) {
if (fromIndex == destIndex) return;
if (fromIndex < destIndex && destIndex < toIndex)
throw new IllegalArgumentException();
// I don't even know what that would do!
if (fromIndex < destIndex) {
Collections.rotate(list.subList(fromIndex, destIndex + 1),
fromIndex - toIndex);
} else {
Collections.rotate(list.subList(destIndex, toIndex + 1),
toIndex - fromIndex);
}
}
void moveTo(列表列表、int-fromIndex、int-toIndex、int-destIndex){
如果(fromIndex==destIndex)返回;
如果(从索引
似乎在一般情况下有效。对于此特定情况
Collections.rotate(arr.subList(0, 6), 3 );
Collections.rotate(arr, 2 );
工作。但是我不知道你要找的一般情况是什么。必须用
toIndex+1
替换toIndex