[英]How move first item of arraylist to last position?
我的代碼轉到最后一個arraylist:
if (listItem.get(listItem.size() - 1).SortNo > 0) {
while (listItem.get(0).SortNo == 0) {
DTO_NightClinic dt = listItem.get(0);
listItem.remove(0);
listItem.add(dt);
}
}
但常見的listItem.remove(0);
它不起作用。 第一項仍然存在於arraylist的第一個位置。
Collections.rotate(list, -1);
只需使用旋轉-1
位置它就可以做你想要的
輸入:
1, 2, 3, 4
輸出:
2, 3, 4, 1
也許Collections.rotate()
似乎是可行的解決方案,但它是一些想要擴展的任務...請參閱Collections.roatate()
的來源
public static void rotate(List<?> lst, int dist) {
...............
reverse(sublist1);
reverse(sublist2);
reverse(list);
}
它遍歷列表的所有項目並應用Collections.reverse()
opearion因此消耗一些時間。
在這里,因為你只是想從List中刪除第一個項目並將其添加到List的尾部,你可以做一個簡單的技巧,如下面的示例...
ArrayList<Integer> arrayList = new ArrayList<Integer>();
for (int i = 1; i < 5; i++) {
arrayList.add(Integer.valueOf(i));
}
System.out.println(arrayList.toString());
// prints [1, 2, 3, 4]
Integer removedItem = arrayList.remove(0);
arrayList.add(removedItem); // adds to the end of the List
System.out.println(arrayList.toString());
// prints [2, 3, 4, 1]
Collections.rotate(list, -1);
/ ...................................
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.