Java Reference
In-Depth Information
Two of the constructors available for
ArrayList
are as follows:
public
ArrayList()
Creates an empty list with an initial capacity of 10. The list increases its capacity as needed by
an unspecified amount.
public
ArrayList(
int
initialCapacity)
Creates an empty list with the specified initial capacity. The list increases its capacity as
needed by an unspecified amount.
12.14
The class
java.util.Vector
, which we described in Chapter 6, is similar to
ArrayList
. Both classes
implement the same interfaces:
java.util.List
, as well as others. Even so,
Vector
contains a few
more methods than
ArrayList
. We will ignore these extra methods, as they mostly are redundant.
You can use either
ArrayList
or
Vector
as an implementation of the interface
List
. For exam-
ple, you could write the following statement to define a list of strings:
List<String> myList =
new
ArrayList<String>();
Now
myList
has only the methods declared in the interface
List
.
Our
ListInterface
is somewhat simpler than Java's
List
. It has fewer methods, and they do
not throw an exception when given an illegal position. We can retain the simplicity of our interface
and still make use of an existing class by using either
ArrayList
or
Vector
in an implementation of
ListInterface
. We will show you how in the next chapter. Although we will use
Vector
, you
could use
ArrayList
just as easily.
C
HAPTER
S
UMMARY
•
A list is an object whose data consists of ordered entries. Each entry is identified by its position within the list.
•
The ADT list specifies operations that add an entry either to the end of a list or at a given position within the
list. Among its other operations are those that retrieve, remove, or replace the entry at a given position.
•
A client manipulates or accesses a list's entries by using only the operations defined for the ADT list.
•
The entries in a bag are unordered, whereas the entries in a list, a stack, a queue, a deque, or a priority queue
do have an order. A list, unlike these other collections, enables you to add, retrieve, remove, or replace an
entry at any given position.
E
XERCISES
1.
If
myList
is an empty list of strings, what does it contain after the following statements execute?
myList.add("A");
myList.add("B");
myList.add("C");
myList.add("D");
myList.add(1, "one");
myList.add(1, "two");
myList.add(1, "three");
myList.add(1, "four");
2.
If
myList
is an empty list of strings, what does it contain after the following statements execute?
myList.add("alpha");
myList.add(1, "beta");
myList.add("gamma");
myList.add(2, "delta");
myList.add(4, "alpha");
myList.remove(2);
myList.remove(2);
myList.replace(3, "delta");