Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArrayList resizing

Tags:

java

arraylist

I have an ArrayList object for which I know the exact size. Is there any way to specify that the ArrayList should not extend its capacity?

List<String> list = null;
int size = getSize(); // gets the exact number of elements I want

list = new ArrayList<String> (size);

for (int i = 0; i < size; i++) {
    list.add("String num: " + i);
}

I don't want the ArrayList to re-size because that takes time which I want to avoid wasting.

like image 846
Sotirios Delimanolis Avatar asked Nov 28 '22 09:11

Sotirios Delimanolis


1 Answers

list = new ArrayList<String> (size);

This will create arraylist with 'size' as initial capacity. As long as you don't add more elements than 'size' there will be no resizing.

Also please be sure that this really takes time in your application. Unless you have profiled and identified this as issue, you will not gain much by randomly optimizing the code.

like image 120
Ashwinee K Jha Avatar answered Dec 04 '22 11:12

Ashwinee K Jha