Java Reference
In-Depth Information
Java will make sure that you add values of an appropriate type. In this case,
because you requested an
ArrayList<String>
, you can add
String
s to the list.
When you ask an
ArrayList
to add a new value to the list, it appends the new value
to the end of the list.
Unlike with simple arrays, printing an
ArrayList
is straightforward because the
ArrayList
class overrides Java's
toString
method. The
ArrayList
version of
toString
constructs a
String
that includes the contents of the list inside square
brackets, with the values separated by commas. Remember that the
toString
method is called when you print an object or concatenate an object to a
String
. As a
result, you can print
ArrayList
s with a simple
println
:
System.out.println("list = " + list);
For example, you can add
println
statements as you add values to the list:
ArrayList<String> list = new ArrayList<String>();
System.out.println("list = " + list);
list.add("Tool");
System.out.println("list = " + list);
list.add("Phish");
System.out.println("list = " + list);
list.add("Pink Floyd");
System.out.println("list = " + list);
Executing this code produces the following output:
list = []
list = [Tool]
list = [Tool, Phish]
list = [Tool, Phish, Pink Floyd]
Notice that you can print the
ArrayList
even when it is empty and each time that
new values are added to the end of the list. The
ArrayList
class also provides an
overloaded version of the
add
method for adding a value at a particular index in the
list. It preserves the order of the other list elements, shifting values to the right to
make room for the new value. This version of
add
takes two parameters: an index
and a value to insert.
ArrayList
s use zero-based indexing, just as arrays and
String
s do. For example, given the preceding list, consider the effect of inserting a
value at index 1:
System.out.println("before list = " + list);
list.add(1, "U2");
System.out.println("after list = " + list);
Search WWH ::
Custom Search