Java Reference
In-Depth Information
List size? 6
Is Miami in the list? True
The location of Denver in the list? 1
Is the list empty? false
[London, Xian, Paris, Seoul, Tokyo]
Tokyo Seoul Paris Xian London
The area of the circle? 12.566370614359172
Since the
ArrayList
is in the
java.util
package, it is imported in line 1. The program
creates an
ArrayList
of strings using its no-arg constructor and assigns the reference to
cityList
(line 6). The
add
method (lines 9-19) adds strings to the end of list. So, after
cityList.add("London")
(line 9), the list contains
add(Object)
[London]
After
cityList.add("Denver")
(line 11), the list contains
[London, Denver]
After adding
Paris
,
Miami
,
Seoul
, and
Tokyo
(lines 13-19), the list contains
[London, Denver, Paris, Miami, Seoul, Tokyo]
Invoking
size()
(line 22) returns the size of the list, which is currently
6
. Invoking
contains("Miami")
(line 24) checks whether the object is in the list. In this case, it returns
true
, since
Miami
is in the list. Invoking
indexOf("Denver")
(line 26) returns the index of
Denver
in the list, which is
1
. If
Denver
were not in the list, it would return
-1
. The
isEmpty()
method (line 28) checks whether the list is empty. It returns
false
, since the list is not empty.
The statement
cityList.add(2, "Xian")
(line 31) inserts an object into the list at the
specified index. After this statement, the list becomes
size()
add(index, Object)
[London, Denver, Xian, Paris, Miami, Seoul, Tokyo]
The statement
cityList.remove("Miami")
(line 35) removes the object from the list.
After this statement, the list becomes
remove(Object)
[London, Denver, Xian, Paris, Seoul, Tokyo]
The statement
cityList.remove(1)
(line 39) removes the object at the specified index
from the list. After this statement, the list becomes
remove(index)
[London, Xian, Paris, Seoul, Tokyo]
The statement in line 43 is same as
System.out.println(cityList);
The
toString()
method returns a string representation of the list in the form of
[e0.toString(), e1.toString(), ..., ek.toString()]
, where
e0
,
e1
, . . . , and
ek
are the elements in the list.
The
get(index)
method (line 47) returns the object at the specified index.
ArrayList
objects can be used like arrays, but there are many differences. Table 11.1 lists
their similarities and differences.
Once an array is created, its size is fixed. You can access an array element using the
square-bracket notation (e.g.,
a[index]
). When an
ArrayList
is created, its size is
0
.
toString()
getIndex()
array vs.
ArrayList