Some material adapted from:
http://java.sun.com/docs/books/tutorial/collections/index.html
Collections
A collection groups multiple elements into a single unit. Examples include the following:
-
A poker hand is a collection of cards.
-
A mail folder is a collection of individual messages.
-
A telephone directory is a collection of name, number pairs.
The Java Collections Framework provides efficient implementation of many common data structures and algorithms. Rather than using simple arrays (which can be tedious to maintain) to store data, a programmer can use the classes provided in the
java.util
package.
ArrayList
ArrayLists provide a way to maintain a list of items. Unlike an array, an ArrayList allows the programmer to insert items at and remove items from arbitrary positions without having to worry about moving the remaining items in the list. An ArrayList can also grow or shrink dynamically.
Some of the key operations of an ArrayList are as follows:
-
add - you may add an object to the end of the list, or at an arbitrary position. Like an array, the first position of an ArrayList is position 0.
-
clear - removes all elements from the list.
-
contains - given an object, contains returns true of the ArrayList contains the object and false otherwise.
-
get - given an index, returns the object at that position in the ArrayList.
-
indexOf - given an object, returns the position of the object in the ArrayList.
-
isEmpty - returns true if the ArrayList is empty and false otherwise.
-
remove - you may remove a particular object, or the object at a particular index.
-
set - given an index and an object, replaces the current object at the specified index with the new object.
-
size - returns the number of objects currently in the ArrayList.
An example that declares and initializes a new ArrayList then adds two Strings to the list follows:
|