Difference between Stack.capacity() and Stack.size()

来源:互联网 发布:魔术师约翰逊生涯数据 编辑:程序博客网 时间:2024/06/07 09:16

http://stackoverflow.com/questions/42884434/difference-between-stack-capacity-and-stack-size



I'm currently doing a check with the Stack class to see if it's full. However, List does not have a isFull() implementation, so I am asking to check if capacity() is the same as size(). According to the docs, size() returns the number of components in this vector, and capacity returns the current capacity of the vector. If I understand correctly, are they the same? And if so, how do I go about checking if my Stack is full?

shareimprove this question
 
1 
Define "full"? A Java Stack isn't bound to a predetermined size. – Elliott Frisch Mar 19 at 8:26
 
What do you mean by "full"? I know what I'd mean by full, in terms of the capacity of the underlying array, but without knowing what you'd mean by full, we can't really answer. – Jon Skeet Mar 19 at 8:26
 
Like if it the stack is at max capacity @JonSkeet – bryancresswell Mar 19 at 8:33
 
What "max capacity" are you talking about though? Are you expecting a "push" operation to fail? – Jon SkeetMar 19 at 8:54
 
There is no defined maximum capacity for a stack. If you want to limit the size of your stack, you will have to check the size yourself. You could implement a derived class, with a push operator that does this automatically. But then what: what so you want to do when the stack is full? Throw an exception? – J.H.Bonarius Mar 19 at 8:54

4 Answers

activeoldestvotes
up vote1down voteaccepted

The Stack datastructure in Java represents a last-in-first out (LIFO) stack of objects. It extends class Vector with five operation such as

  1. push
  2. pop
  3. peek item at the top of the stack
  4. Check stack is empty and
  5. search for an item in the stack

when the Stack classs would be like as follows

public class Stack extends Vector {}

When the stack is created it contains no items. Coming to stack capacity and size

Size - Number of elements a stack contains at present

Capacity - Number of elements it is capable of holding

The Push operation is implemented as follows

public E push(E item) {    addElement(item);    return item;}

addElement method belongs to Vector class which helps to insert a new element into the Vector

public synchronized void addElement(E obj) {    modCount++;    ensureCapacityHelper(elementCount + 1);    elementData[elementCount++] = obj;}

ensureCapacityHelper allows to check whether the Vector inside is capable of adding a new element or not. If it does not have enough space to hold the new element the Vector grows

 private void ensureCapacityHelper(int minCapacity) {    // overflow-conscious code    if (minCapacity - elementData.length > 0)        grow(minCapacity);} /** * The maximum size of array to allocate. * Some VMs reserve some header words in an array. * Attempts to allocate larger arrays may result in * OutOfMemoryError: Requested array size exceeds VM limit */private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;private void grow(int minCapacity) {    // overflow-conscious code    int oldCapacity = elementData.length;    int newCapacity = oldCapacity + ((capacityIncrement > 0) ?                                     capacityIncrement : oldCapacity);    if (newCapacity - minCapacity < 0)        newCapacity = minCapacity;    if (newCapacity - MAX_ARRAY_SIZE > 0)        newCapacity = hugeCapacity(minCapacity);    elementData = Arrays.copyOf(elementData, newCapacity);}

Arrays.copyOf is a native method would allocate a new memory space with newCapacity and copies the data from old memory location to new location.

shareimprove this answer
 
up vote1down vote

The size is the current number of elements in the stack.

The capacity is an internal detail that tells you the maximum items that would fit in the Vector. However, this is not really relevant as it will expand automatically when the capacity is reached.

shareimprove this answer
 
 
No, you are taking to many steps at once. Capacity shows the currently available reserved memory space. Yes it changes "automatically", but it is not irrelevant information. In certain memory limited devices you could require a check, which could indicate you have to free up memory before a vector can increase. – J.H.Bonarius Mar 19 at 8:39
 
It is an internal detail, and it is the reason why ArrayList no longer exposes this information. – john16384Mar 19 at 8:46
 
Let me guess, you're not programming embedded devices... – J.H.Bonarius Mar 19 at 8:56
 
I donot see how this is relevant to this question. Can you clarify? – john16384 Mar 19 at 9:00
 
If you are developing for very memory limited situations, like in low cost embedded devices, you have to manage memory properly. So of you have a vector that has grown a lot in the past (thus has a large capacity) but now only holds a few elements, it might be a good idea and even necessity to resize that vector, to free up memory for other variables. For C++ a vector::shrink_to_fit, was introduced to ease this. But it was not introduced until the 2011 standard! – J.H.Bonarius Mar 19 at 9:15 
up vote0down vote

Stack extends Vector and you can check javadoc for this class.

int size() -> Returns the number of components in this vector.(max elements in vector)

int capacity() -> Returns the current capacity of this vector.(current elements in vector)

The difference between capacity() and size() in java.util.Vector is that capacity() returns how many elements it can store whereas the size() gives the no.of elements in the Vector at the time of method call. Capacity of a vector is usually declared within the constructor itself.

shareimprove this answer
 
 
You should explain what "capacity" means – J.H.Bonarius Mar 19 at 8:40
 
@J.H.Bonarius update – Max Krivich Mar 19 at 8:42
 
Good, but you reversed the explanations: size gives the amount of elements currently on the stack, whilecapacity gives the current amount of reserved memory for the stack. If by adding elements the capacity is exceeded, the stack will be moved to a newly allocated large peice of memory. – J.H.Bonarius Mar 19 at 8:48
up vote0down vote

stack.size() - gives the current size i.e., total number of elements pushed to the stack

stack.capacity() - gives the current capacity i.e., array size like 10 or 20 etc... i.e., as soon as you pushes 10 elements to the stack, your stack capacity gets doubled.

Internally Stack uses Vector and Vector is a dynamic growing array. Also, for a Stack, you can't manually set the capacityIncrement factor, rather the stack itself manages internally, you can lookhere

shareimprove this answer
 
1 
Capacity usually doubles when a threshold is exceeded. 10, 20, 30 will this not occur. More like 64, 128, 256,.... – J.H.Bonarius Mar 19 at 8:49
 
@J.H.Bonarius Like Buddy memory allocation en.wikipedia.org/wiki/Buddy_memory_allocation? – Rajasuba Subramanian Mar 19 at 8:53
 
@J.H.Bonarius You can look the answer above added more details – javaguy Mar 19 at 8:59
 
No, is it dynamic allocation. The vector is stored is one block of sequential memory. This means the wholevector needs to be copied when it is reallocated. This can be a costly operation for large vectors. – J.H.Bonarius Mar 19 at 9:00

0 0
原创粉丝点击