Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - "Rotating" Objects in A LinkedList - Is LinkedList.addLast(LinkedList.removeFirst()) Good Or Bad Programming?

In my Java application both of the following will compile and run, and produce the desired result.

//"Rotate" the list items one place to the left.
myLinkedList.addLast(myLinkedList.removeFirst());

And a "rotation" in the opposite direction

//"Rotate" the list items one place to the right.
myLinkedList.addFirst(myLinkedList.removeLast());

Both "rotations" only require one line of code each, but I'm wondering if this is the right way to go about it? Are there any pitfalls in this approach?

Is there a better, more robust, less error-prone way of doing the same as I have above which would require more than one line of code to achieve, and if so please explain why.

like image 678
The Thing Avatar asked Jul 21 '10 21:07

The Thing


3 Answers

Seems fine to me. If you had a truly circular buffer which was full you could just move the "start/end" index, but I think the linked list approach will work pretty well. In particular it's still O(1).

like image 64
Jon Skeet Avatar answered Oct 15 '22 07:10

Jon Skeet


I suggest using Collections.rotate.

like image 2
Tom Hawtin - tackline Avatar answered Oct 15 '22 09:10

Tom Hawtin - tackline


I would implement it exactly as you have.

myLinkedList.addLast(myLinkedList.removeFirst());

The only way I can see this being "bad programming" is if the list is shared between threads and your method rotates an element from one end to the other without holding a lock (I am not aware of any concurrent Queue implementation that can rotate atomically.)

like image 1
finnw Avatar answered Oct 15 '22 08:10

finnw