Java Reference
In-Depth Information
Display 14.3
Golf Score Program
(part 3 of 3)
Sample Dialogue
This program reads golf scores and shows
how much each differs from the average.
Enter golf scores:
Enter a list of nonnegative numbers.
Mark the end of the list with a negative number.
69 74 68
—
1
Average of the 3 scores = 70.3333
The scores are:
69.0 differs from average by —1.33333
74.0 differs from average by 3.66667
68.0 differs from average by —2.33333
TIP: Use
trimToSize
to Save Memory
ArrayList
s automatically increase their capacity when your program needs them to
have additional capacity. However, the capacity may increase beyond what your program
requires. Also, when your program needs less capacity in an
ArrayList
, the
ArrayList
does not automatically shrink. If your
ArrayList
has a large amount of excess capacity,
you can save memory by using the method
trimToSize
to shrink the capacity of an
ArrayList
. If
list
is an
ArrayList
, an invocation of
list.trimToSize()
will shrink
the capacity of the
ArrayList list
down to the size of
list
, so that there is no unused
capacity in
list
. Normally, you should use
trimToSize
only when you know that the
ArrayList
will not need its extra capacity later.
trimToSize
■
PITFALL: The
clone
Method Makes a Shallow Copy
★
There are situations in which you would like to make an independent copy of an
ArrayList
object; that is, you would like to make a deep copy of the
ArrayList
object. (Deep copying and shallow copying were discussed in Chapter 5 ; you may
want to review that material.) For example, if you define a class with a private
instance variable of an
ArrayList
type, then you would like an accessor method
to return a deep copy of the
ArrayList
stored in the private instance variable. The
reason you want a deep copy is the same as the reason that you want a deep copy of
an array instance variables. This was discussed in Chapter 6 in the subsection entitled
“Privacy Leaks with Array Instance Variables.” It would be a good idea to review that
subsection before going on with reading this subsection.
As we have often observed, the assignment operator merely copies a reference so that
you have another name for the object being copied. So, you do not have an independent