Java Reference
In-Depth Information
Display 14.1 Some Methods in the Class ArrayList (part 4 of 4)
MAKE A COPY
public Object[] toArray()
Returns an array containing all the elements on the list. Preserves the order of the elements.
public Type [] toArray( Type [] a)
Returns an array containing all the elements on the list. Preserves the order of the elements. Type can
be any class types. If the list will fit in a , the elements are copied to a and a is returned. Any elements
of a not needed for list elements are set to null . If the list will not fit in a , a new array is created.
(As we will discuss in Section 14.2, the correct Java syntax for this method heading is
public <Type> Type[] toArray(Type[] a)
However, at this point we have not yet explained this kind of type parameter syntax.)
public Object clone()
Returns a shallow copy of the calling ArrayList . Warning : The clone is not an independent copy.
Subsequent changes to the clone may affect the calling object and vice versa. (See Chapter 5 for a
discussion of shallow copy.)
EQUALITY
public boolean equals(Object other)
If other is another ArrayList (of any base type), then equals returns true if and only if both
ArrayList s are of the same size and contain the same list of elements in the same order. (In fact, if
other is any kind of list , then equals returns true if and only if both the calling ArrayList and
other are of the same size and contain the same list of elements in the same order. Lists are dis-
cussed in Chapter 16.)
Why Are Some Parameters of Type Base_Type and Others of Type Object ?
Look at the table of methods in Display 14.1. In some cases, when a parameter is naturally an
object of the base type, the parameter type is the base type, but in other cases, it is the type
Object .
For example, look at the add methods and the second remove method in the table. The
add methods have a parameter of the base type; the remove method has a parameter of
type Object . Why the difference in parameter types? The class ArrayList implements a
number of interfaces and inherits methods from various ancestor classes. These interfaces
and ancestor classes specify that certain parameters have type Object .
For example, in Chapter 7 we explained that the parameter for the equals method is
always of type Object because the method heading is inherited from the class Object . In
other cases, the designers of the ArrayList class were free to specify the parameter types
for the method.
 
Search WWH ::




Custom Search