What's meant by parameter (int initial capacity) in an arraylist
Asked Answered
K

7

31

What's meant by parameter (int initialCapacity) in an ArrayList, I thought it's the number of elements but it didn't work when I did this:

public class MyClass {
    private ArrayList<Integer> arr;
    public MyClass(int n_elements) {
        arr = new ArrayList<Integer>(n_elements);
    }
}
Kata answered 13/11, 2010 at 12:24 Comment(0)
S
59

It's the initial capacity, i.e. the number of items that ArrayList will allocate to begin with as the internal storage of items.

ArrayList can contain "any number of items" (as long you have the memory for it) and when doing large initial insertions you can tell ArrayList to allocate a larger storage to begin with as to not waste CPU cycles when it tries to allocate more space for the next item.

Example:

ArrayList<Integer> list = new ArrayList<>(2);
list.add(10); // size() == 1
list.add(20); // size() == 2, list is "filled"
list.add(30); // size() == 3, list is expanded to make room for the third element
Shanley answered 13/11, 2010 at 12:27 Comment(8)
I object to the word "default" in the first sentence. The default number is the size that's allocated if you don't put a number in the parentheses.Tonnie
@Carl: You are correct. Changed it to initial capacity, as to conform to the Java docs.Shanley
To be precise: "any number of items" is limited to Integer.MAX due to the fact that arrays in java are indexed by ints (as of Java 6).Rocco
@Willi: Well, if you are going to allocate more than 2^31-1 values I believe you are having a memory problem rather than having ArrayList running out of capacity.Shanley
Integer.MAX is about 2 Billions (not 2^31-1) which takes up to 16GB of RAM (on a 64 Bit Machine) which is not soo big today.Rocco
@Willi: Uhm, 2^31-1 is about 2 billions. And you rarely store bitvalues, so that 16GB (of object pointers) will have to be multiplied by the actual size of the objects you store.Shanley
@Shanley Right about the 2^31-1, screwed that up. Of course you have to consider the size of the objects, but the collection just contains the references, so the memory usage of the collection is just 16 GB.Rocco
This is always a gotcha for me. Whenever I want to use the capacity instantiation of say an ArrayList, I really want capacity=size instead of size=0. You know, sort of like Integer integerArray = new Integer[capacity].Sortilege
E
18

Practically speaking, it's how many elements you can add to the ArrayList before it resizes in the background, which can save you some cycles if used correctly.

Ensiform answered 13/11, 2010 at 12:30 Comment(0)
D
9

Capacity is the size of the internal storage of the objects. The internal storage is always greater than or equal to the size() of the list (so that it can contain all elements).

public class Main {
    public static void main(String[] args) throws Exception {

        ArrayList<Integer> arr = new ArrayList<>();
        System.out.println("initial size = " + arr.size()); // 0
        System.out.println("initial capacity = " + getCapacity(arr));

        for (int i = 0; i < 11; i++)
            arr.add(i);

        System.out.println("size = " + arr.size()); // 11
        System.out.println("capacity = " + getCapacity(arr));
    }

    static int getCapacity(ArrayList<?> l) throws Exception {
        Field dataField = ArrayList.class.getDeclaredField("elementData");
        dataField.setAccessible(true);
        return ((Object[]) dataField.get(l)).length;
    }
}

Running this gives:

initial size = 0
initial capacity = 10
size = 11
capacity = 16
Displume answered 13/11, 2010 at 12:35 Comment(0)
L
5

Under the hood, ArrayList is essentially a dynamic array. Every time you instantiate using new Arraylist<>() what's happening is that an array is created to hold the values you want to store whose default capacity, not to be confused with size, is 10.

Every time you add a value that would increase the size beyond capacity a new array is created whose capacity is one more than 150% the previous capacity with the contents of the previous array copied within.

If you have a general idea what size the resulting list will be, or are certain but desire the flexibility afforded from using arraylists over arrays you can set the capacity to prevent this repetitive process of creating new arrays, copying the contents of the old array in the new one, and getting rid of the old one -- which will otherwise increase in occurrences proportional to the size of the list.

Lathy answered 5/2, 2015 at 6:17 Comment(0)
F
1

pardon my English. The question asked is 'what is the meaning or function of the parameter initial capacity in the ArrayList?' If I'm not wrong. I explained that whenever an array is created the default capacity is 10. And I explained that the array resizes itself when the number added had is more than it's the bucket. In case of time complexity, I suggested that perfect capacity should be added. Take a look at this code via Geeks for Geeks:

import java.util.*;

class Student {

    public static void main(String[] arg) throws Exception
    {
        try {

            
            ArrayList<String> numbers
                    = new ArrayList<String>(3);

           
            numbers.add("10");
            numbers.add("20");
            numbers.add("30");

            // Print the ArrayList
            System.out.println("ArrayList: " + numbers);

            
            System.out.println(
                    "Increasing the capacity of ArrayList numbers to store up to 500 elements.");

            numbers.ensureCapacity(500);

            System.out.println(
                    "ArrayList numbers can now store upto 500 elements.");
        }

        catch (NullPointerException e) {
            System.out.println("Exception thrown : " + e);
        }
    }
}
Filmore answered 31/12, 2021 at 3:42 Comment(0)
F
0

By default, ArrayList is set to nothing less than 10. However, it may take more than the default capacity based on the fact that it can expand. To be on a safer side, it is reasonable to set the initial capacity to avoid another declaration of ArrayList. Hence, the initial capacity is primitive datatype int. it is meant to take the number of lists we are adding.

Filmore answered 28/12, 2021 at 12:56 Comment(1)
This answer answers nothing. It's hard to read and what more than that - contains wrong information. Look at the accepted answer for comparison.Beaded
D
-1

Arraylist size and capacity are different.

For Example: In below arraylist initial capacity = 3, and size of the list = 0 as there is no elements in the list yet.

ArrayList list = new ArrayList(3);

Dabchick answered 26/1, 2021 at 21:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.