Java Reference
In-Depth Information
class, which can be used to store an unlimited number of objects. FigureĀ 11.3 shows some
methods in
ArrayList
.
java.util.ArrayList<E>
+ArrayList()
+add(o: E): void
+add(index: int, o: E): void
+clear(): void
+contains(o: Object): boolean
+get(index: int): E
+indexOf(o: Object): int
+isEmpty(): boolean
+lastIndexOf(o: Object): int
+remove(o: Object): boolean
Creates an empty list.
Appends a new element
o
at the end of this list.
Adds a new element
o
at the specified index in this list.
Removes all the elements from this list.
Returns true if this list contains the element
o
.
Returns the element from this list at the specified index.
Returns the index of the first matching element in this list.
Returns true if this list contains no elements.
Returns the index of the last matching element in this list.
Removes the first element o from this list. Returns true
if an element is removed.
Returns the number of elements in this list.
Removes the element at the specified index. Returns true
if an element is removed.
Sets the element at the specified index.
+size(): int
+remove(index: int): boolean
+set(index: int, o: E): E
F
IGURE
11.3
An
ArrayList
stores an unlimited number of objects.
ArrayList
is known as a generic class with a generic type
E
. You can specify a concrete
type to replace
E
when creating an
ArrayList
. For example, the following statement creates
an
ArrayList
and assigns its reference to variable
cities
. This
ArrayList
object can be
used to store strings.
ArrayList<String> cities =
new
ArrayList<String>();
The following statement creates an
ArrayList
and assigns its reference to variable
dates
. This
ArrayList
object can be used to store dates.
ArrayList<java.util.Date> dates =
new
ArrayList<java.util.Date> ();
Note
Since JDK 7, the statement
ArrayList<AConcreteType> list =
new
ArrayList<AConcreteType>();
can be simplified by
ArrayList<AConcreteType> list =
new
ArrayList<>();
The concrete type is no longer required in the constructor thanks to a feature called
type inference
. The compiler is able to infer the type from the variable declaration. More
discussions on generics including how to define custom generic classes and methods
will be introduced in ChapterĀ 19, Generics.
type inference
ListingĀ 11.8 gives an example of using
ArrayList
to store objects.
L
ISTING
11.8
TestArrayList.java
1
import
java.util.ArrayList;
2
import
ArrayList
Search WWH ::
Custom Search