You are here:

C++/TrimToSize() method

Advertisement


Question
Hi 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.

Answer
trimming 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 ;
       }

   }  

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


vijayan

Expertise

my primary areas of interest are generic and template metaprogramming, STL, algorithms, design patterns and c++09. i would not answer questions about gui and web programming.

Experience

over 15 years

Education/Credentials
post graduate engineer

©2012 About.com, a part of The New York Times Company. All rights reserved.