+ 1

I have some difficulties in my java code with regards to vectors. Please help

In my code, After using setsize(12), why is the vec.capacity(); (on code line 18) giving the output of 20(please check the code output and tell me why is the new size 20) ? And why trimtosize func does not remove the null elements? https://code.sololearn.com/cpc9sofwase9/?ref=app

8th Apr 2020, 1:53 PM
Merlyn J
8 ответов
+ 2
You start with an empty vector: capacity = 10 size = 0 Then you add 5 elements: capacity = 10 size = 5 Then you change the size to 12: 12 > 10 -> capacity increases capazity = 20 size = 12 Then you trim capacity to size: capacity = 12 size = 12 Do you now understand it?
8th Apr 2020, 5:30 PM
Denise Roßberg
Denise Roßberg - avatar
+ 1
Size and capacity are not the same. Vector<Integer> vec = new Vector<>(30); now print vec.size() and vec.capazity() The vector is empty so size = 0. But capacity is 30. Means, you have zero elements in the vector but could store 30 if you want. setSize() changes the size. trimToSize() trims the capazity of this vector to be the current size. For example you create this Vector with a capacity of 30. But later there are only 5 elements in it, so you could trim the vector (capacity = 5).
8th Apr 2020, 5:05 PM
Denise Roßberg
Denise Roßberg - avatar
+ 1
But my question here is how is vec.capacity() on the 18th line of the code showing output of 20 when initial capacity is 10?
8th Apr 2020, 5:25 PM
Merlyn J
+ 1
And in my code, if you see the output there are only 5 elements and the rest are null, so why doesn't trimtosize() trim the vector to 5 elements?
8th Apr 2020, 5:25 PM
Merlyn J
+ 1
Denise Roßberg Can you explain Then you change the size to 12: 12 > 10 -> capacity increases capazity = 20 size = 12 This👆 (why capacity becomes 20 and isn't 12+10=22) ?
9th Apr 2020, 7:16 AM
Merlyn J
+ 1
Merlyn J Because the capacity doubles. The capacity at the beginning is 10. 12 elements does not fit in the vector, so the capacity gets 20. If you change size to 21 the capacity gets 40. Another example: You start with a capacity of 12. Now you change the size to 13. The new capacity gets 24. If you change the size to 25 the capacity gets 48 and so on...
9th Apr 2020, 11:39 AM
Denise Roßberg
Denise Roßberg - avatar
+ 1
https://www.javatpoint.com/java-vector may be helpful in this regard.
11th Apr 2020, 1:48 PM
narayanaprasad
narayanaprasad - avatar
0
Merlyn J About the 5 elements. After changing the size to 12, your array is filled with null. Those are also elements. That's the reason why the size gets 12.
8th Apr 2020, 5:35 PM
Denise Roßberg
Denise Roßberg - avatar