Tricky Tricks ›› Programming Tricks ›› Java Tricks ›› Vector (N) Does Not Have N Elements

Vector (N) Does Not Have N Elements

Java Programming Tricks

Vector (n) does not have n elements:

 In Java, arrays cannot be resized dynamically. If you want a 
 dynamic data structure with random access, you use a Vector. 
 
 A vector has a current size and a capacity, the number of elements 
 it can ho1d without having to grow, again. 
 
 Trap 
 
 The constructor Vector (int n) builds a vector with capacity ~, 
 not with size n, as a C~ programmer would certainly expect. 
 
 Vector v = new Vector (100); 
 
 v.setElementAt(new Double,3.14), 0,); // throws ArrayIndex OutOfBoundsException
 
 If you want a vector with 100 elements, use 
 
 Vector v = new Vector(100); 
 
 v.setSize(100); 
 
 v.setElementAt(new Double(3.14), 0); // OK 
 

Partners