C++/TrimToSize() method
Expert: vijayan - 2/5/2009
QuestionHi Again,
You helped me earlier with my Java code a little. I have asked the java quys but they haven't got back to me yet. I am writing to you again because you are very prompt in replying.
I will not paste all my code, my methods are working except for this one. I don't understand what the problem is? it doesn't trim my array!
Below I have pasted my data members and my trimToSize method.
could you tell me why plz?
http://rafb.net/p/YZvZni98.html
thanks.
Answertrimming the array should
a. create a new array of *size* (not objects.length-size) elements
b. copy the elements into the new array
c. make the new array the array we use from now on
d. adjust the capacity to reflect the change.
public void trimToSize ()
{
if( size < objects.length ) // the array could be trimmed
{
// allocate a new array to hold size elements
Object[] temp = new Object [ size ];
// copy elements into the new array
for( int i = 0 ; i<size ; ++i )
temp[i] = objects[i] ;
// switch to the new array
objects = temp ;
// capacity == size after the array is trimmed
capacity = size ;
}
}