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

落花浮王杯 提交于 2021-01-27 06:16:07

问题


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.


回答1:


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).




回答2:


I suggest using Collections.rotate.




回答3:


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.)



来源:https://stackoverflow.com/questions/3304129/java-rotating-objects-in-a-linkedlist-is-linkedlist-addlastlinkedlist-rem

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!