I\'m a little confused on what it means about ArrayLists holding references to objects. Can someone give me an example on how this is shown in code? Also, can arraylist have an
You have to start making distinctions between variables, values, and objects.
Variables are containers. They contain values.
Values can be of two types, primitive and reference. Reference values are pointers to objects.
Objects are data structures which also have behavior.
So in
Object var = new Object();
var
is a variable. new Object()
is a new instance creation expression that evaluates to a value of type Object
, that value is a reference to an object of type Object
. That value is then assigned to var
.
You can then use var
to invoke a method
var.toString();
The runtime environment will evaluate var
, which produces a reference value, retrieve the referenced object, and invoke the method. You can reassign the value stored in var
by doing
var = someOtherValue;
Now var
will hold a new value.
An ArrayList
uses an array behind the scenes. An array is a special object where its elements (which you can think of as fields) are themselves variables.
So
Object[] arr = new Object[10];
is an array of type Object
which contains ten variables. These variables contain values of type Object
. Again, these values are references. You can evaluate them or you can reassign them.
arr[3].toString();
arr[7] = "maybe a string";
arr[9] = arr[9]; // possible, but makes no sense