You are here:

C++/set method

Advertisement


Question
Hi again Vijayan,
This would be my last question I promise :)
Again having in mind the following are my data members:
size, capacity and private Object[] objects;
My SET Method doesn't work! When I give it an index which is used already (i.e 0) it replace the existing value but if I give it an index that is not used but is within the range of the capacity, it doesn't do anything!

public void setElementAt (Object element, int index)
  {
     if (index>= capacity)
     {
     System.out.println(" The index " + index +" does not exist!");
     return;
     }

     objects[index] = element;
  
  }
thanks for your time in advance.


Answer
you need to adjust the size to reflect the new element which has been added.

public void setElementAt (Object element, int index)
{
   if( ( index >= capacity ) || ( index < 0 ) )
   {
       System.out.println(" The index " + index +" does not exist!");
       return;
   }

   objects[index] = element;
   
   if( size < (index+1) ) size = index + 1 ;

}

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++11. i would not answer questions about gui and web programming.

Experience

about 15 years or so

Education/Credentials
post graduate engineer

©2016 About.com. All rights reserved.