简体   繁体   中英

Element count and element data are of different values in java.util.Vector

When I use java.util.Stack to add an integer, in debug mode, i find that the element count is one & the elementdata object array is of length 10. Once the data is pushed into the stack, I see the stack object refers to the length one (ie elementcount) instead of elementdata array length.

Stack<Integer> stack = new Stack<Integer>();
stack.push(5);
//Inside the Vector class, i see that add element uses:-
public synchronized void addElement(E obj) {
        modCount++;
        ensureCapacityHelper(elementCount + 1);
        elementData[elementCount++] = obj;
}

The elementcount is one & elementData length is 10 but the stack.size() is still one. How is the stack object mapped to elementcount?

That's right. Because at the beginning elementData , by design, is created with a size greater than the actual number of elements it contains: 10 elements in this case.

elementCount keeps track of the current number of elements, and as soon as this number is greater than the size of elementData , a new array is created with room to spare. This happens every time the current data array gets filled.

The algorithm to increase the size is implementation dependant, some possible examples include: creating a new array with double the size of the original, or creating a new array with 50% more elements. Either way, the elements are copied from the original array to the new one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM