Search code examples
javaarraylistdeep-copycall-by-value

Rearrange order of an ArrayList


I want to rearrange an ArrayList by iterating through it and copying each element to a specific place in a new list.

In this case I want to move an element to the end of the list. For example, if the list is ABCDE and j == B then the new list should be ACDEB.

Here's my code:

private ArrayList<Job> schedule;
private ArrayList<Job> tempSchedule;

...

schedule = input;
tempSchedule = new ArrayList<Job>(schedule.size());

...

private void moveJob(int j) {
    for(int i = 0; i < schedule.size(); i++) {
        if(i == j) { //move to the end
            tempSchedule.set(schedule.size()-1, schedule.get(i));
        } else {
            if(i > j && i <= schedule.size() -1) { //move one position back
                tempSchedule.set(i - 1, schedule.get(i));
            } else { //same position
                tempSchedule.set(i, schedule.get(i));
            }
        }
    }
    schedule = tempSchedule;
    u++;
}

Right now I get an IndexOutOfBoundsException: Index: 0, Size: 0 at tempSchedule.set

I guess the problem is with this line

tempSchedule = new ArrayList<Job>(schedule.size());

Also please explain how to make deep copies.

Edit: Thanks for all the answers. I got it to run by simply removing the item and adding it at the end, like suggested.

The reason I wanted to construct a new list is because I might have to do more complex rearrangements at some point.


Solution

  • First, go read the javadoc on ArrayList and collections.

    new ArrayList(capacity) doesn't copy, it just allocates a list with that capacity. To copy the list (and it's not a clone, it's a by reference copy, again you need to go back to basics) would be new ArrayList(oldArrayList).

    Secondly, Your test has size 0, so there's no objects in it, so get(0) (correctly and as per spec) throws an index out of bounds exception because your list is empty.

    Beyond that, neither set nor get will modify the list, so if you had created your copy correctly and it's contents were ABCD and you executed that operation, it's contents would then be ABCB. what you want is.

    X = tempSchedule.remove(i) // removes element at I
    tempSchedule.add(X)        // adds element to end of list