Will
ArrayList<int>(20);
create a maximum of 20 array or is it an illegal syntax?
Will
ArrayList<int>(20);
create a maximum of 20 array or is it an illegal syntax?
This will not compile since the element type cannot be a primitive. Use Integer
instead.
new ArrayList<Integer>(20);
will create a list backed by an array with an initial capacity of 20.
Perhaps you should read API documentation for ArrayList
first.
You can create an ArrayList
instance like this:
List<Integer> list = new ArrayList<Integer>(20);
In this case, 20
is initial capacity.
From Java7, you can omit the parameterized type.
List<Integer> list = new ArrayList<>(20);
You can't use primitive type as type parameter. Why don't Java Generics support primitive types? also helpful.
ArrayList<int>(20);
is illegal, since you can't use primitives as generic types nor put them into the standard collections.
ArrayList<Integer>(20);
would create a list with a basic capacity of 20 integer objects but it can be resized as needed.
Assuming that you change int
to Integer
(You can't use generics with primitives), that will create an ArrayList
of initial size 20.
It can still grow past that limit, as per the JavaDocs at http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#ArrayList(int):
Constructs an empty list with the specified initial capacity.
If your question is about the memory allocation part and considering you use a syntax like:
ArrayList<Integer> arr = new ArrayList<Integer>(20);
It just allocates memory for 20 Integer
. It still an empty ArrayList
though.
This is intended to be used for performance reasons but for most common situation there isn't a big difference (without the memory preallocation that is).
Generally we should use the default constructor for any Collection object If we don't know the required size. Because think about the situation you are creating an ArrayList of size 500 but actually you are adding only 5 items into it. That is not recommended. We can not use primitives in Generics for type safety in Collections. This restriction is for providing backward compatibility to older version java codes(Older than 1.5).
For more details kindly have a look here: Link 1, Link 2, Link 3, Link 5