开发者

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

开发者 https://www.devze.com 2023-01-25 03:00 出处:网络
What\'s meant by parameter (int initialCapacity)开发者_JS百科 in an ArrayList, I thought it\'s the number of elements but it didn\'t work when I did this:

What's meant by parameter (int initialCapacity)开发者_JS百科 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);
    }
}


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 list = new ArrayList<Integer>(2);
list.add(1); // size() == 1
list.add(2); // size() == 2, list is "filled"
list.add(3); // size() == 3, list is expanded to make room for the third element


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.


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


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.


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);
        }
    }
}


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.


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);

0

精彩评论

暂无评论...
验证码 换一张
取 消