Best way to rearrange an ArrayList in Java

后端 未结 1 446
伪装坚强ぢ
伪装坚强ぢ 2021-02-07 12:50

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

相关标签:
1条回答
  • 2021-02-07 13:16

    Use the JDK's swap method

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

    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.

    0 讨论(0)
提交回复
热议问题