2

假设我有一个值为 {1、4、6、54、9、34、21、53} 的 ArrayList。

我需要将值 1、4 和 6 移动到 34 之后的索引。我还需要将值 21 和 53 移动到 54 的前面。所以我的 ArrayList 应该看起来像 {21, 53, 54, 9, 34, 1, 4, 6};

我尝试使用:

Collections.rotate(arr.subList(0, 2), -3); Collections.rotate(arr.subList(6, 7), 2);

但是,所有这些都是在子列表中旋转索引。

关于如何使这项工作的任何想法?

4

2 回答 2

4

我注意到

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);
  }
}

似乎在一般情况下有效。

于 2012-01-30T02:37:32.920 回答
1

对于这种特殊情况,

Collections.rotate(arr.subList(0, 6), 3 );
Collections.rotate(arr, 2 );

作品。但我不知道您要查找的一般情况是什么。

于 2012-01-30T02:45:21.920 回答