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 element that is a reference to itself? Thanks!
2 Answers
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
Comments
It means instead of copying the object byte-for-byte, a reference to the location of memory where the object is stored is put in the list.
List<Object> objects = new ArrayList<Object>();
Object myObject = new Object();
objects.add(myObject);
// objects contains one reference to myObject
objects.get(0).modify();
// myObject modified
Note that primitive values (int for example) will be copied.
list.add(hello);and thenString anotherString = list.get(0);, thenhelloandanotherStringwould both refer to the same String object, because they share the same reference. This also shows that a list won't copy the passed object of theaddmethod. It just store its reference. And it will return that reference if you access it usingget(index).