Arrays and References
An Introduction with Examples in Java |
Prof. David Bernstein
|
Computer Science Department |
bernstdh@jmu.edu |
new
operator is used to allocate memory
for arraysnew
operator returns a referenceWe can now look more closely at what happens when an array is declared and when it is instantiated.
[ ]
OperatorAn array of objects is really an array of references.
final
The fact that arrays are reference types leads to some "surprises"
about arrays that are declared to be final
.
Specifically, a reference can only be assigned to the array once,
but values/references can be assigned to the elements of the array
multiple times.
The relational equals operator (i.e., ==
) compares
references. To compare elements, use the
array's .equals()
method or
the Arrays.equals()
method, but be careful since they rely on
the elements .equals()
method which may not do what you want.
A copy of the reference is passed so the formal parameter is an alias for the actual parameter.
clone()
Method
clone()
creates a shallow copy so each element in
copy
will contain the same reference as the
corresponding element in original
java.util.Arrays
Revisited
The methods in the java.util.Arrays
utility class can change
the elements in the arrays that they are passed because
arrays are reference types.
max()
method)...
after the type of the last
formal parameter