Click here to Skip to main content
15,896,502 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Java
<pre>List<Integer> l=new ArrayList<>();
       l.add(1);
       l.add(2);
       l.add(3);
       l.add(4);
       System.out.println("Element at 0th index: "+l.get(0));
       Iterator i=l.iterator();
        while(i.hasNext())
        {
            Integer obj=(Integer)(i.next());
            int o=obj;
            System.out.println(o);
        }


ouput:
Element at 0th index: 1
1
2
3
4


What I have tried:

<pre lang="java"><pre>List<Integer> l=new ArrayList<>();

Upon changing the above line to the following
<pre><pre lang="java"><pre>List<Integer> l=new ArrayList<>(2);

the same output is obtained. Could anyone explain the use of argument passed in ArrayList as ArrayList(2) ?
Posted
Updated 17-Jul-18 20:00pm

1 solution

It;s the initial capacity of the ArrayList: ArrayList (Java Platform SE 7 )[^] - if it isn't specified then it starts with a capacity of 10. When you specify it as 2 it allocates just two elements to start with.

It's for efficiency - if you know how many elements you are going to use, then you can start with that as the capacity and save the constant reallocation until you reach it.
See here: List<T> - Is it really as efficient as you probably think?[^] - it's C# based but the Java ArrrayList does exactly the same thing, for the same reasons.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900