ArrayList class is the most straight-forward of several
classes that Java provides to represent groups or collections of
ArrayListwithout 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.
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
add(itemToAdd)method to add items.
get(i)method to get the item at index
set(i, newItem)to replace it. Valid indices range from
theList.size() - 1.
remove(i)method to remove the item at index
theList.get(theList.size() - 1).