1

e.g.

class StackElement {
    String method;
    int state;
}

Stack<StackElement> stack;

I want to get a deep copy of this stack, which contains StackElement defined by myself.

  1. Does Java provide a suitable API for this purpose ?

  2. If not, how to implement it in a simple and general way ?

JackWM
  • 10,085
  • 22
  • 65
  • 92

2 Answers2

1

The easiest way is to follow these simple steps:

  1. make your StackElement implement Serializable;
  2. serialize the complete stack into a byte array;
  3. deserialize right back into a deep copy.

The downside is less-than-top performance.

Do note that Stack is considered an archaeological artefact, obsoleted way back in Java 1.2 by LinkedList, which can be used as a stack. The reason it is obsoleted is that each method is synchronized, adding very little to thread safety of client code, but introducing a performance hit and even possible deadlocks.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
0

I'm not sure if there's a special issue with your case, but you could look at some options here.

Community
  • 1
  • 1
Andres Olarte
  • 4,380
  • 3
  • 24
  • 45