Java - Rotating objects in LinkedList - LinkedList.addLast (LinkedList.removeFirst ()) Good or bad programming?

In my Java application, both of them will be compiled and run, and you will get the desired result.

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

And the "rotation" in the opposite direction

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

Both "rotations" require only one line of code, but I wonder if this is the right thing to do? Are there any pitfalls in this approach?

Is there a better, more reliable, less error prone way to do the same as mine above, which will require more than one line of code, and if so, explain why.

+5
source share
3 answers

, . , , "/", , . , O (1).

+4

I would do it exactly the same as you.

myLinkedList.addLast(myLinkedList.removeFirst());

The only way to see that this is โ€œbad programmingโ€ is that the list is split between threads and your method rotates the element from one end to the other without holding the lock (I don't know any parallel Queuethat can rotate atomically.)

+1
source

All Articles