user1177178
user1177178

Reputation: 21

How do you move a group of objects to a different location inside of an ArrayList using Java?

Let's say I have an ArrayList with the values {1, 4, 6, 54, 9, 34, 21, 53}.

I need to move the values 1, 4, and 6 to the index after 34. I also need to move the values 21 and 53 in front of 54. So my ArrayList should look like {21, 53, 54, 9, 34, 1, 4, 6};

I tried using:

Collections.rotate(arr.subList(0, 2), -3); Collections.rotate(arr.subList(6, 7), 2);

However, all this does is rotate the indexes inside of the subLists.

Any ideas on how to make this work?

Upvotes: 2

Views: 596

Answers (2)

Dawood ibn Kareem
Dawood ibn Kareem

Reputation: 79838

For this specific case,

Collections.rotate(arr.subList(0, 6), 3 );
Collections.rotate(arr, 2 );

works. But I don't know what the general case you're looking for is.

Upvotes: 1

Louis Wasserman
Louis Wasserman

Reputation: 198103

I notice that

Collections.rotate(arr.subList(0, 6), -3);

moves 1, 4, and 6 to the index after 34, as desired. I suspect this trick would be generally applicable, depending on whether or not the target index is before or after the sublist being moved.

<T> void moveTo(List<T> list, int fromIndex, int toIndex, int destIndex) {
  if (fromIndex == destIndex) return;
  if (fromIndex < destIndex && destIndex < toIndex) 
    throw new IllegalArgumentException();
    // I don't even know what that would do!
  if (fromIndex < destIndex) {
     Collections.rotate(list.subList(fromIndex, destIndex + 1),
       fromIndex - toIndex);
  } else {
     Collections.rotate(list.subList(destIndex, toIndex + 1),
       toIndex - fromIndex);
  }
}

seems to work in the general case.

Upvotes: 4

Related Questions