2012-01-30 25 views
2

比方說,我有一個值爲{1,4,6,54,9,34,21,53}的ArrayList。如何使用Java將一組對象移動到ArrayList中的不同位置?

我需要將值1,4和6移動到34之後的索引。我還需要移動值54和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

我注意到

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

似乎在一般情況下工作。

+0

必須用'toIndex'替換'toIndex + 1' – 2016-12-06 10:27:48

1

對於這個特定的情況下,

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

作品。但我不知道你正在尋找的一般情況是什麼。

相關問題