Java Reference
In-Depth Information
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 later need its extra capacity.
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 rea-
son you want a deep copy is the same as the reason that you want a deep copy of an
array instance variables and that was discussed in Chapter 6 in the subsection enti-
tled “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 copy. You have what's known as a shallow copy . For example, assume
that Pet is a class with the usual kinds of accessor methods and consider the follow-
ing code:
ArrayList<Pet> petList1 = new ArrayList<Pet>();
< Some code to set the instance variables of elements of petList1 . >
ArrayList<Pet> petList2 = petList1;
petList2 and petList1 are just two names for the same ArrayList object. Making a
change to petList1 or to an element of petList1 will also change petList2 because
they are the same list.
If you want an independent copy (deep copy) of petList1 , you might think the fol-
lowing would give you your independent copy:
ArrayList<Pet> petList2 = petList1.clone();
Search WWH ::




Custom Search