Reputation: 1
I would like to know why the primitive int didn't change as the size of the array changes. Doesn't the primitive point to the array reference?
List<String> list = new ArrayList<>();
int num = list.size();
list.add("item1");
list.add("item2");
System.out.println(num); //why is the num variable still equals to zero?
Upvotes: 0
Views: 39
Reputation: 106410
When you make a call to size()
, you're getting a snapshot of the size of the collection at that instant in time. You don't get any extra reference to it, since it's just a numerical value. It can never hold a reference of any kind, it'll always be a raw, numerical value.
The size()
method has the ability to reference the internal state of the collection, so it's better to use that instead of storing it in another variable.
Upvotes: 1
Reputation: 3118
A primitive points to an area of memory that holds a static (not to be confused with the static
keyword) value, they are not able to reference a variable within a class. Essentially when the primitive is changed it now points to a new memory location that has the new number inside of it.
In addition the size variable in the List is also a primitive. That primitive may seem to change but it is only because it is changed each time that something is added or removed from the list.
Upvotes: 1
Reputation: 285403
Primitives can't point since they're primitives; they hold a value and that's it. If you want the value to change, you must change it. Consider using an observer type pattern if you want to change the num variable when the List changes, or even better, doing away with num completely and just call list.size()
when you need its size.
Upvotes: 2