Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279990

ArrayList resizing

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.

Upvotes: 5

Views: 22656

Answers (4)

Francisco Spaeth
Francisco Spaeth

Reputation: 23903

What you could do to limit an ArrayList would be to override the ensureCapacity(int minCapacity) method like in the following sample:

public static class MyArrayList<T> extends ArrayList<T> {

    @Override
    public void ensureCapacity(int minCapacity) {
        if (minCapacity > 10) {
            throw new IllegalArgumentException();
        }
        super.ensureCapacity(minCapacity);
    }

}

A small test could be done with the following code:

public static void main(String[] args) {
    MyArrayList<String> items = new MyArrayList<String>();

    for (int i = 0; i < 15; i++) {
        try {
            items.add("itm " + i);
            System.out.println("succeeded to insert " + i);
        } catch (IllegalArgumentException e) {
            System.out.println("not able to insert " + i);
        }
    }

    System.out.println("items are: " + items);
}

This will print:

succeeded to insert 0
succeeded to insert 1
succeeded to insert 2
succeeded to insert 3
succeeded to insert 4
succeeded to insert 5
succeeded to insert 6
succeeded to insert 7
succeeded to insert 8
succeeded to insert 9
not able to insert 10
not able to insert 11
not able to insert 12
not able to insert 13
not able to insert 14
items are: [itm 0, itm 1, itm 2, itm 3, itm 4, itm 5, itm 6, itm 7, itm 8, itm 9]

Upvotes: 2

Ashwinee K Jha
Ashwinee K Jha

Reputation: 9317

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.

Upvotes: 16

Faraway
Faraway

Reputation: 1117

If you know the exact size, and it will not be extended in the future, then why don't you just use String arrays.

String[] strArray=new String[size];

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1500865

The ArrayList won't resize if you don't add more elements than it has capacity for. You've created the list with the right capacity, so it should be fine.

You could create a list which threw an exception if you tried to exceed the original capacity, but it's not clear why that would be useful to you here.

Upvotes: 5

Related Questions