ArrayList
Class
The ArrayList
class is the most straight-forward of several
classes that Java provides to represent groups or collections of
objects.
ArrayList
without knowing in
advance how many items the list will eventually hold,
and you can add or remove items as you need.
ArrayList
, you do not need to
give them individual variable names. Instead, you refer to them by
their location, or index, in the list.
ArrayList
.
For example, the following code fragment creates an empty deck of cards, adds 3 cards to the deck, and then prints the first and third card in the deck.
ArrayList<Card> deck = new ArrayList<Card>();
deck.add(new Card("Ace", "Clubs"));
deck.add(new Card("Queen", "Hearts"));
deck.add(new Card("5", "Spades"));
System.out.println("First card: " + deck.get(0));
System.out.println("Third card: " + deck.get(2));
A few more details:
ArrayList
, it always starts out
empty. You can get the current size using the size()
method.
add(itemToAdd)
method to add items.get(i)
method to get the item at index
i
, or set(i, newItem)
to replace it.
Valid indices range from 0
to
theList.size() - 1
.
remove(i)
method to remove the item at index
i
.
theList.get(theList.size() - 1)
.