Collections.rotate: Shifting Elements Circularly
You'll learn how Collections.rotate shifts list elements in a circular pattern, moving items from one end to wrap around to the other.
What Is Circular Rotation?
Imagine a circular conveyor belt with items on it. When you rotate it, items move around the circle—what falls off one end reappears at the other. That's exactly what Collections.rotate does with a list.
The method takes two parameters: the list to rotate and the distance (how many positions to shift). A positive distance rotates elements to the right; a negative distance rotates left.
How rotate Works
When you call Collections.rotate(list, distance):
- Each element shifts
distancepositions toward the end of the list - Elements that "fall off" the end wrap around to the beginning
- Elements at the beginning may wrap to the end (depending on direction)
Right rotation (positive distance): Elements near the end move to the front.
Left rotation (negative distance): Elements near the front move to the end.
Examples in Plain English
Consider a list: [A, B, C, D, E]
rotate(list, 2)→[D, E, A, B, C](last 2 elements moved to front)rotate(list, -2)→[C, D, E, A, B](first 2 elements moved to end)rotate(list, 7)→ Same asrotate(list, 2)(7 mod 5 = 2, wraps around)
When to Use rotate
Use rotate when you need to shift elements cyclically—useful in scheduling algorithms, ring buffers, or puzzles where you manipulate sequences.
Key Takeaway: Collections.rotate shifts list elements by a distance in a circular fashion, wrapping elements from one end to the other based on positive (right) or negative (left) distance values.