Why ArrayList instead of Stack in the implementation of Memento pattern?

6

As you all know, the Memento pattern is the default that saves different states of objects and then retrieves them.

The intent is not to retrieve the "last" entry and then remove it? This is a stack, right?

So why do examples use ArrayList by taking the index element (quantity - 1) and does not use Stack direct?

Do you have an explanation for this?

Example:

I'm using C #, but I can understand java, so this question is for both.

In C # I'm using List and to recover I'm using

TextoMemento estadoSalvo = estados.ElementAt(estados.Count -1);
        estados.RemoveAt(estados.Count - 1);

Why not Stack ?

    
asked by anonymous 31.12.2014 / 12:50

2 answers

5

In Java, classes that inherit from Vector ( including Stack ) are thread-safe , ie they carry the overhead to prevent two different threads from accessing at the same time collection. The use of a ArrayList (that is not thread-safe ) avoids this overhead , and therefore should be preferable to Stack a unless this feature is important in your application.

Furthermore, if you prefer to use a semantically appropriate class, there is Deque and its various implementations, which can also be used as if it were a stack:

Método do Stack | Método equivalente do Deque
----------------+----------------------------
push(e)         | addFirst(e)
pop()           | removeFirst()
peek()          | peekFirst()

(Of course, this answer is valid for Java only. I do not have enough experience in C # to comment on the libraries of that language.)

    
31.12.2014 / 13:07
3

Examples are just examples. Each one does the way it thinks best. If you want to know why and are not explained where you read, you should ask the person who did the example. He must have a reason.

Mibibsonbr has already given a good reason for this to be done with Java. In C # the implementation of the class Stack<T> , at least in its generic form (I have never used the legacy form) is not a competitor. If you need competition you should use ConcurrentStack<T> .

In fact this practical example in C # shows that the stack is used.

    
31.12.2014 / 13:16