I'm doing work on different stacks and what I'm studying, increases its size to double when we introduce the (2 ^ n +) 1 element.
But what is the growth policy of java.util.Stack and java.util.Array?
I'm doing work on different stacks and what I'm studying, increases its size to double when we introduce the (2 ^ n +) 1 element.
But what is the growth policy of java.util.Stack and java.util.Array?
The class java.util.Stack
extends java.util.Vector
, which will define much of its functionality.
Vector
allows you to specify in your constructor both the initial capacity and the increment of the internal vector when capacity is exceeded, but this constructor is not available in subclass Stack
.
This means that the inner vector will always start with the number of default elements, which is 10
, and double in size when expanding: 20
, 40
, 80
, ...
However, the ensureCapacity(n)
method can force faster growth. Basically, the method expands the vector to ensure that it can receive at least more% of elements% without overflowing the capacity. In the current implementation, the method first checks whether doubling capacity is sufficient, otherwise it resizes the internal vector to n
. This also means that you can not expand the vector by less than its double, not by creating an alternate implementation.
The class capacidade atual + n
will always have the size of the internal vector being a power of java.util.ArrayDeque
, as its documentation declares.
For linear growth, you can use the 2
class, which implements java.util.LinkedList
, the same interface implemented by java.util.Deque
.
It's never too much to remember that every implementation has its advantages and disadvantages.
For example, vector-based implementations are faster for random access and for insertion of multiple elements in sequence, especially when the quantity is known and as long as the quantity is not as large as, say, half the available memory.
Lists based on element strings may be necessary when the list is too large, occupying most of the memory and is changed quite frequently so it is not possible to use vectors since making a copy of the vector would occupy more than 100 % of memory.