2010-03-04 35 views
0

我有一個包含5個元素[a,b,c,d,e]的列表。基於用戶選擇,我想改變顯示順序,並想知道是否有功能可以給我一個新排序的列表。列表中元素的旋轉

e.g. If user selects d, e to move 1 position up, the resultant order will be [a,b,d,e,c] 
e.g. If user selects b, e to move 1 position up, the resultant order will be [b,a,c,e,d] 
e.g. If user selects b, d, e to move 1 position up, the resultant order will be [b,a,d,e,c] 

是否有開箱即用的功能可以做到這一點?

+2

我沒有得到你的要求 - 具體而言,我不認爲我明白你的意思是「移動一個位置」。在第一個例子中,我希望根據您的描述輸出爲[a,b,d,e,c]。你能澄清嗎? – 2010-03-04 10:29:43

+0

你是對的,我犯了一個錯誤,我已經糾正了問題 – Sam 2010-03-04 10:52:46

+0

移動一個位置向上意味着元素被移動到左側,之前的元素移動到右側的位置 – Sam 2010-03-04 12:11:36

回答

2

在這兩種情況下,你都交換相鄰的元素。基本上,x=a[i]; a[i]=a[j]; a[j] = x;

+0

我現在使用Collections.swap來實現這個邏輯 – Sam 2010-03-05 06:08:46

0

看起來像一個簡單的要求,JDK集合,共同集合或谷歌集合都沒有答案。

我會建議寫一個:)

+0

我已經看到Collections.rotate,但它旋轉整個列表。我的邏輯似乎有缺陷解決這個問題,因此這個問題 – Sam 2010-03-04 12:13:19