Course contentsShow
← Java
Lesson 1235 of 2,87028. Collections Utility ClassFree lesson

Rotate with Positive and Negative Distances

Understand direction: positive distance rotates right, negative rotates left, modulo handles large values.

Rotate with Positive and Negative Distances

What you'll learn: How the direction and magnitude of the distance parameter control rotation in Collections.rotate().


Understanding Rotation Direction

When you call Collections.rotate(list, distance), the sign of the distance determines which way elements shift:

  • Positive distance → elements rotate to the right (toward the end)
  • Negative distance → elements rotate to the left (toward the beginning)

Think of it like a circular conveyor belt: positive numbers move items clockwise, negative numbers move them counterclockwise.

How Direction Works

List<String> letters = new ArrayList<>(Arrays.asList("A", "B", "C", "D", "E"));

// Rotate right by 2 positions
Collections.rotate(letters, 2);
System.out.println(letters);  // [D, E, A, B, C]

// Reset
letters = new ArrayList<>(Arrays.asList("A", "B", "C", "D", "E"));

// Rotate left by 2 positions (same as right by -2)
Collections.rotate(letters, -2);
System.out.println(letters);  // [C, D, E, A, B]

Handling Large Distance Values

Java automatically applies modulo arithmetic when the distance exceeds the list size. This prevents unnecessary full rotations:

List<Integer> nums = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));

// Rotating by 7 is the same as rotating by 7 % 5 = 2
Collections.rotate(nums, 7);
System.out.println(nums);  // [4, 5, 1, 2, 3]

// Rotating by -8 is the same as rotating by -8 % 5 = -3
Collections.rotate(nums, -8);
System.out.println(nums);  // [4, 5, 1, 2, 3]

The modulo operation ensures efficiency—rotating a 5-element list by 1,000 positions only does the minimal work needed.

Key Takeaway: Positive distances rotate right, negative distances rotate left, and Java uses modulo to handle distances larger than the list size efficiently.