Thursday, April 14, 2011

Best way to rearrange an ArrayList in Java

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.

From stackoverflow
  • 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.

    Jon Skeet : Doh. Didn't even see that. Deleting my answer...
    Elijah : I only remembered it because I was looking at it today for my project. It is in one of the dark corners of the JDK.
    Jeff Olson : Very cool, I don't think I've ever used that method either, but it definitely could come in handy.

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.