Reputation: 1261
I have the following array:
ArrayList<Integer> myArray = new ArrayList<Integer>();
I also have a variable 'someNum':
int someNum = 12;
My code:
public class Main {
public static void main(String[] args){
int someNum = 12;
ArrayList<Integer> myArray = new ArrayList<Integer>(someNum);
int arraySize = myArray.size();
System.out.println(arraySize);
}
}
Console: '0'
Why is it printing '0'
?
I checked the ArrayList documentation is states that array.size();
"Returns the number of elements in this list."
What am I doing wrong?
Upvotes: 2
Views: 165
Reputation: 522
You're calling the ArrayList
constructor that accepts as its parameter the initial capacity of the list.
You want instead
myArray = new ArrayList<Integer>();
myArray.add(someNum);
at which point myArray.size()
will return 1
.
Upvotes: 2
Reputation: 234795
The size is 0 because you haven't added any members. The argument to the constructor is the initial capacity, not the initial size (or the first element).
Upvotes: 9
Reputation: 279920
The constructor used in
ArrayList<Integer> myArray = new ArrayList<Integer>(someNum);
sets the initial capacity of the ArrayList
. This has nothing to do with the number of elements in the ArrayList
.
Upvotes: 3