在 Java 中重新排列 ArrayList 的最佳方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/657581/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Best way to rearrange an ArrayList in Java
提问by Jens Jansson
What is the best way to rearrange elements in an list? I need the ability to move elements to move elements in the list, one step back or forward in the index. I was thinking of getting the index of the item, adding it at index -1 / +2 and removing the old reference.
重新排列列表中元素的最佳方法是什么?我需要能够移动元素来移动列表中的元素,在索引中后退或前进一步。我正在考虑获取项目的索引,将其添加到索引 -1 / +2 并删除旧引用。
Is there a faster way to handle rearranging without creating duplicates in the list in the process.
有没有更快的方法来处理重新排列而不在此过程中在列表中创建重复项。
回答by Elijah
Use the JDK's swap method
使用JDK的swap方法
The JDK's Collections class contains a method just for this purpose called Collections.swap. According to the API documentation this method allows you to "swap the elements at the specified positions in the specified list."
JDK 的 Collections 类包含一个专门用于此目的的方法,称为Collections.swap。根据 API 文档,此方法允许您“交换指定列表中指定位置的元素”。
I suggest this solution so that you don't have to remove elements from the List and so that you don't have to roll your own swap method. Also, it looks like this method has been around since the 1.4 release of Java so it should work for most of the modern JDKs.
我建议使用此解决方案,这样您就不必从 List 中删除元素,也不必推出自己的交换方法。此外,这种方法似乎自 Java 1.4 版本以来就已经存在,因此它应该适用于大多数现代 JDK。

