走动项的ArrayList [英] Moving items around in an ArrayList

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

问题描述

所以,我还是相当新的Java和我一直在玩弄的ArrayList的 - 我想要实现是这样做的方法:

So I'm still fairly new to Java and I've been playing around with ArrayList's - what I'm trying to achieve is a method to do something like this:

Item 1
Item 2
Item 3
Item 4

所以我想能够移动的项目在列表中,除非它已经在这种情况下,将保持不变顶部。例如,如果第3项被移到名单将是:

So 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

显然,我与挣扎的部分是动起来的一部分。这是如何可以实现任何提示或code样品是多少AP preciated。

Obviously, 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:

<一个href=\"http://docs.oracle.com/javase/6/docs/api/java/util/Collections.html#rotate%28java.util.List,%20int%29\">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:

请注意,该方法可以有效地应用到子列表移动一个
  或列表中的多个元素,而preserving的顺序
  剩余的元件。例如,下面的语句移动元件
  在索引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):

Col​​lections.rotate(list.subList(J,K + 1),-1);

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

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