What happens if you push an item into a stack but the initial capacity has already been met?

StackOverflow https://stackoverflow.com/questions/22902275

  •  28-06-2023
  •  | 
  •  

Pergunta

Stack initial capacity: 5
Object[0] = 'H'
Object[1] = 'a'
Object[2] = 'p' 
Object[3] = 'p' 
Object[4] = 'y' 

What happens if you try these executions:

s.push('i');
s.push('s');

Also does a stack implementation using an array have a peek method?

PS. I don't have a computer and i'm merely on my phone asking this. I was just reading a book and this came up as a question...

Foi útil?

Solução

The initial capacity is the starting size of the stack's internal array. Once the initial capacity is already met, most implementations will resize the underlying array.

Outras dicas

Depends how the stack was implemented. It will cause a stack overflow, and how that is handled is also up to how you implemented your stack.

Ideally, the stack implementation should know when it is at full capacity. When the stack is at capacity and a push is attempted, it will generally throw an exception and not attempt to add an element at all. It is then up to the caller to catch these exceptions and handle them appropriately.

So in short: A good stack implementation will provide error checking and not crash a whole program, a poorly written one will crash. This is using an array as you mentioned, which can have a peek() or top() method.

EDIT: In reply to changing to an ArrayList implementation, then you can't technically overflow since the ArrayList will dynamically grow. But say you set a soft capacity internally, where your stack is not allowed to grow larger than 100 elements. Then YOUR implementation will overflow, not because the ArrayList is full, but because your soft capacity was reached.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top