ArrayList resizing

I have an ArrayList object for which I know the exact size. Is there a way to indicate that the ArrayList should not expand 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 change because it takes a while, which I want to avoid.

+3


source to share


4 answers


list = new ArrayList<String> (size);

      

This will create an arraylist with "size" as the initial capacity. As long as you don't add more items than "size", there will be no resizing.



Also make sure it really takes time in your application. Unless you've profiled and identified this as a problem, you won't get much by accidentally optimizing your code.

+14


source


ArrayList

will not resize unless you add more elements than it has. You've created a list with the right capacity, so everything should be fine.



You can create a list that would throw an exception if you tried to exceed the original capacity, but it is not clear why this would be useful to you here.

+5


source


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

String[] strArray=new String[size];

      

+2


source


What you could do to constrain ArrayList

would be to override the method ensureCapacity(int minCapacity)

as in the following example:

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 can 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]

      

+1


source







All Articles