Java Reference
In-Depth Information
System
.
out
.
println
(
"Retrieving by index:"
);
for
for
(
int
int
i
=
0
;
i
<
al
.
size
();
i
++) {
System
.
out
.
println
(
"Element "
+
i
+
" = "
+
al
.
get
(
i
));
}
}
}
The older
Vector
and
Hashtable
classes predate the Collections framework, so they provide
additional methods with different names:
Vector
provides
addElement()
and
elementAt()
.
You will see these in legacy code, but you should use the
Collections
methods
add()
and
get()
instead. Another difference is that the methods of
Vector
are synchronized, meaning
that they can be accessed from multiple threads (see
Synchronizing Threads with the syn-
chronized Keyword
)
. This does mean more overhead, though, so in a single-threaded applic-
the contents of a
List
as an array. The
java.util.Arrays
class features an
asList()
meth-
od, which converts in the other direction, from an array to a
List
. With the Variable Argu-
ments feature of modern Java (described in
Variable argument lists
), you can create and pop-
ulate a list in one call to
Arrays.asList()
. For example:
// ArraysAsListDemo.java
List
<
String
>
firstNames
=
Arrays
.
asList
(
"Robin"
,
"Jaime"
,
"Joey"
);
In days of yore, you needed to be more explicit, like so:
List
<
String
>
lastNames
=
Arrays
.
asList
(
new
new
String
[]{
"Smith"
,
"Jones"
,
"MacKenzie"
});
Java does indeed get less verbose as time goes by!