Dynamic Array Allocation

Dynamic Array Allocation

Java does not offer arrays that can be extended at run time, for primitives or Objects, so it is common to use a Vector for a set of elements that needs to be able to grow. Once the set is complete, if your code needs repeated access to the elements, perhaps to sort them, it would be more efficient to be able to manipulate an array. Fortunately, it is easy to obtain an array from a Vector. Suppose you have placed numerous Strings in a Vector. To obtain the corresponding String array takes just three lines of code:

     int count = yourVector.size();    String[] yourArray = new String[count];    yourVector.copyInto(yourArray);

If the Vector is not referenced again, the garbage collector will be able to recover the memory it required.


Share the Post: