在Java中重新排列ArrayList的最佳方法 [英] Best way to rearrange an ArrayList in Java

查看:331
本文介绍了在Java中重新排列ArrayList的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

重新排列列表中元素的最佳方法是什么?我需要能够移动元素来移动列表中的元素,在索引中向后或向前一步。我正在考虑获取项目的索引,将其添加到索引-1 / +2并删除旧的引用。

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.

是否有更快的方法来处理重新排列而不在过程中在列表中创建重复项。

Is there a faster way to handle rearranging without creating duplicates in the list in the process.

推荐答案

使用JDK的交换方法

JDK的Collections类包含一个专门用于此目的的方法,称为 Collections.swap 。根据API文档,此方法允许您交换指定列表中指定位置的元素。

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."

我建议您使用此解决方案,以便您没有从列表中删除元素,以便您不必滚动自己的交换方法。此外,看起来这个方法自Java 1.4发布以来就已存在,所以它应该适用于大多数现代JDK。

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.

这篇关于在Java中重新排列ArrayList的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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