在 ArrayList 中移动项目 [英] Moving items around in an ArrayList

查看:29
本文介绍了在 ArrayList 中移动项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在玩ArrayLists.我想要实现的是一种方法来做这样的事情:

I've been playing around with ArrayLists. What I'm trying to achieve is a method to do something like this:

Item 1
Item 2
Item 3
Item 4

我正在尝试将列表中的项目向上移动,除非它已经在顶部,在这种情况下它会保持不变.例如,如果项目 3 被移动,列表将是:

I'm trying to be able to move items up in the list, unless it is already at the top in which case it will stay the same. For example, if item 3 was moved the list would be:

Item 1
Item 3
Item 2
Item 4

根据我目前的一点点理解,我想要一些类似的东西:

From my small understanding at the moment then I would want something along the lines of:

IF arrayname index is not equal to 0
THEN move up
ELSE do nothing

我正在努力解决的部分是向上移动"部分.非常感谢有关如何实现这一点的任何提示或代码示例.

The part I'm struggling with is the "move up" part. Any tips or code samples of how this could be achieved are much appreciated.

推荐答案

我在寻找答案时遇到了这个老问题,我想我会发布我找到的解决方案,以防其他人经过这里寻找一样.

I came across this old question in my search for an answer, and I thought I would just post the solution I found in case someone else passes by here looking for the same.

对于交换 2 个元素,Collections.swap 很好.但是如果我们想要移动更多元素,有一个更好的解决方案,包括创造性地使用 Collections.sublist 和 Collections.rotate,直到我看到这里描述的时候才想到:

For swapping 2 elements, Collections.swap is fine. But if we want to move more elements, there is a better solution that involves a creative use of Collections.sublist and Collections.rotate that I hadn't thought of until I saw it described here:

http://docs.oracle.com/javase/6/docs/api/java/util/Collections.html#rotate%28java.util.List,%20int%29

这是引述,但也可以自己阅读整篇文章:

Here's a quote, but go there and read the whole thing for yourself too:

请注意,此方法可以有用地应用于子列表以移动一个或列表中的更多元素,同时保留列表的顺序剩余元素.例如,以下习语移动元素在索引 j 向前到位置 k(必须大于或等于至 j):

Note that this method can usefully be applied to sublists to move one or more elements within a list while preserving the order of the remaining elements. For example, the following idiom moves the element at index j forward to position k (which must be greater than or equal to j):

Collections.rotate(list.subList(j, k+1), -1);

这篇关于在 ArrayList 中移动项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆