Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
321 views
in Technique[技术] by (71.8m points)

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

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);
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...