If i need to initialize a static final Collection

I have one collection defined this way, without a specified size –

private final static Collection<String> mycollection = new ArrayList<String>();   
static {
    mycollection.add("mystr");
}

There is also a constructor that takes a size, e.g.

private final static Collection<String> mycollection = new ArrayList<String>(1);    
static {
    mycollection.add("mystr");
}

Since the Collection is final, should I be constructing it so that it is a specific size?

Answer

Setting the initial size of an ArrayList, reduces the number of times the re-allocation of internal memory has to occur. If you create an ArrayList without setting capacity within constructor it will be created with a default value, which I guess is 10. ArrayList is a dynamically re sizing data structure, implemented as an array with an initial (default) fixed size. If you know your upper bound of items, then creating the array with initial length is better I suppose.

As per the documentation of ArrayList() constructor :

Constructs an empty list with an initial capacity of ten.

Whereas , ArrayList(int initialCapacity)

Constructs an empty list with the specified initial capacity.

Since the Collection is final, should I be constructing it so that it is a specific size?

The reference variable is final , it can only point to one object , in this case the ArrayList . This doesn’t imply that the contents or properties of ArrayList itself cannot be changed . Refer JLS 4.12.4

Once a final variable has been assigned, it always contains the same value. If a final variable holds a reference to an object, then the state of the object may be changed by operations on the object, but the variable will always refer to the same object.

Leave a Reply

Your email address will not be published. Required fields are marked *