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
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
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.
you can try this simple code, Collections.swap(list, i, j) is what you looking for.
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.
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:
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:
A simple swap is far better for "moving something up" in an ArrayList:
Because an ArrayList uses an array, if you remove an item from an ArrayList, it has to "shift" all the elements after that item upward to fill in the gap in the array. If you insert an item, it has to shift all the elements after that item to make room to insert it. These shifts can get very expensive if your array is very big. Since you know that you want to end up with the same number of elements in the list, doing a swap like this allows you to "move" an element to another location in the list very efficiently.
As Chris Buckler and Michal Kreuzman point out, there is even a handy method in the Collections class to reduce these three lines of code to one:
To
Move
item in list simply add:To
Swap
two items in list simply add:Moving element with respect to each other is something I needed a lot in a project of mine. So I wrote a small util class that moves an element in an list to a position relative to another element. Feel free to use (and improve upon ;))
Applying recursion to reorder items in an arraylist