Java Reference
In-Depth Information
•
ArrayList()
creates an empty array list with an initial
capacity
(storage
space)oftenelements.Oncethiscapacityisreached,alargerarrayiscreated,
elements fromthecurrentarrayarecopiedintothelargerarray,andthelarger
arraybecomesthenewcurrentarray.Thisprocessrepeatsasmoreelementsare
added to the array list.
•
ArrayList(Collection<? extends E> c)
createsanarraylistcon-
taining
c
's elements in the order in which they are returned by
c
's iterator.
NullPointerException
is thrown when
c
contains the null reference.
•
ArrayList(int initialCapacity)
createsanemptyarraylistwithan
initial capacity of
initialCapacity
elements.
IllegalArgumentEx-
ception
is thrown when
initialCapacity
is negative.
Listing 5-1
demonstrates an array list.
Listing 5-1.
A demonstration of an array-based list
import java.util.ArrayList;
import java.util.List;
class ArrayListDemo
{
public static void main(String[] args)
{
List<String> ls = new ArrayList<>();
String[] weekDays = {"sun", "mon", "tue", "wed",
"thu", "fri", "sat"};
for (String weekDay: weekDays)
ls.add(weekDay);
dump("ls:", ls);
ls.set(ls.indexOf("wed"), "wednesday");
dump("ls:", ls);
ls.remove(ls.lastIndexOf("fri"));
dump("ls:", ls);
}
static void dump(String title, List<String> ls)
{
System.out.print(title+" ");
for (String s: ls)