Using Arrays Instead of Vectors

Vectors are powerful and flexible containers for all kinds of objects. Their main advantage over arrays is that their size grows dynamically as needed. The disadvantages are

  • Many type casts may be needed because a Vector can hold any kind of objects.

  • Vectors carry some overhead compared to a corresponding array. Actually, Vectors use an array internally to store their data. Thus, using a Vector requires an additional indirection step and an additional object when compared to using an array.

  • The Vector access methods are synchronized, which also results in some performance tradeoff. The fact that the size of an array cannot change may help to achieve thread safety without synchronization.

For these reasons, in some cases it may make sense to use arrays instead of Vectors, especially if the size of the structure does not change frequently. However, using an array instead of a Vector is not free of costs. You can't change the size of an array. If an array must be extended, you have to allocate a new array and copy its entire contents. Thus, for structures that frequently change size, sticking to a Vector may be a better choice. An alternative that is also used internally by the Vector class is to allow that the array is larger than necessary. The actual size is stored in a separate variable in that case.

Table 8.1 shows some Vector operations and the corresponding counterparts for arrays.

Table 8.1. Vector Operations and the Corresponding Counterparts for Array Access
Vector Array
(MyObject) v.elementAt (i);
v[i];

v.addElement (o);
v2 = new MyObject[v.length+1];
System.arraycopy (v, 0, v2, 0, v.length);
v2 [v.length] = o;
v = v2;

v.removeElementAt (i);
v2 = new MyObject [v.length-1];
System.arraycopy (v, 0, v2, 0, i-1);
System.arraycopy (v, i+1,  v2, i, v.length - i);
v = v2;

v.insertElementAt (o, i);
v2 = new MyObject [v.length+1];
System.arraycopy (v, 0, v2, 0, i-1);
System.arraycopy (v, i+1, v2, i+1, v.length);
v2[i] = o;
v = v2;

v.setElementAt (o, i);
v[i] = obj;


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset