Why ArrayList rather than Stack in the Memento standard implementation?

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

Is not the intention to retrieve the" last " to enter and then remove it? This is a pile, right?

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

Do you have an explanation for this?

Example:

I'm using C#, but I can understand java, so this question it fits both of us.

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?

Author: Maniero, 2014-12-31

2 answers

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

No more, if you prefer to use a class semantically appropriate, there is the 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()

(naturally, this answer applies to Java only. I don't have enough experience in C# to comment on the libraries of this language.)

 6
Author: mgibsonbr, 2014-12-31 12:07:05

Examples are just examples. Everyone does what they see fit. If you want to know why and it is not explained where you read, you should ask who made the example. He must have a motive.

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

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

 3
Author: Maniero, 2020-09-16 15:00:46