How do I copy a stack in Java?

前端 未结 6 660
星月不相逢
星月不相逢 2020-12-03 21:03

I have a stack A and I want to create a stack B that is identical to stack A. I don\'t want stack B to simply be a pointer to A -- I actually want to create a new stack B th

6条回答
  •  星月不相逢
    2020-12-03 21:36

    The Stack class is a sub-class of AbstractList.

    Simply treat it like an AbstractList, iterate through the elements in the stack using the get(int index) method, from 0 to the length of your list/stack, and add the elements to the new stack.

    This won't copy the elements - it will add the elements to the new stack. If you need to copy the elements as well, you'll need to go another level deep and create copies of the elements, and add those to the new stack.

    You can do full (or "deep") copies, by using the clone method, but note that the object must implement the Clonable interface in order to get deep copies of objects.

提交回复
热议问题