Home > front end >  How to change "capacityIncrement" value post initialization in Vector?
How to change "capacityIncrement" value post initialization in Vector?

Time:05-19

In vector by default initialCapacity is set at 10 and capacityIncrement is also set at 10.

Thus if we do -

Vector<String> vector = new Vector<>();

we have initialCapacity and capacityIncrement both set at 10.

However, we have the flexibility to set our own values.

For example, if we do -

Vector<String> vector = new Vector<>(5,5);

we have initialCapacity and capacityIncrement both set at 5.

Now, post initialization, we have the methods -

void setSize(int size)
void ensureCapacity(int capacity)
void trimToSize()

to change both size and capacity as per our needs.

But, how can we change the capacityIncrement value post initialization as per our need?

CodePudding user response:

You can do it using reflect.Field as below:

public static void main (String[] args){
    Vector<String> vector = new Vector<>(5, 5);
    System.out.println(getMyCapacityIncrement(vector));
    setMyCapacityIncrement(vector, 9);
    System.out.println(getMyCapacityIncrement(vector));
}
private static void setMyCapacityIncrement(Vector<String> myVector, int capacityIncrement){
    try {
        Field field = myVector.getClass().getDeclaredField("capacityIncrement");
        field.setAccessible(true);
        field.set(myVector, capacityIncrement);
        field.setAccessible(false);
    } catch (NoSuchFieldException | IllegalAccessException e) {
        e.printStackTrace();
    }
}

private static int getMyCapacityIncrement(Vector<String> myVector) {
    try {
        Field field = myVector.getClass().getDeclaredField("capacityIncrement");
        field.setAccessible(true);
        return field.getInt(myVector);
    } catch (NoSuchFieldException | IllegalAccessException e) {
        e.printStackTrace();
        return -1;
    }
}

CodePudding user response:

Why do you need to change the capacity increment after creation?

If you know the (approximate) size of the resulting List, you can create it with a suitable capacity, and the default increment is tuned to be good, see ArrayList Efficiency and size.

The reason a method to change the increment doesn't exist in ArrayList is because it's unnecessary. That kind of micro tuning is not required (or would be achievable with ensureCapacity() anyway), so it makes the API cleaner not to have it.

  • Related