|
An ordered collection is called a List. A concrete
implementation of a List
is ArrayList:
Object
AbstractCollection (implements Collection)
AbstractList (implements List)
AbstractSequentialList
LinkedList
ArrayList
Vector
Stack
AbstractSet (implements Set)
HashSet
TreeSet (implements SortedSet)
AbstractMap (implements Map)
HashMap
TreeMap (implements SortedMap)
WeakHashMap
Dictionary
Hashtable (implements Map)
Properties
ArrayList implements the List
as a resizeable
array, but that is just one possible implementation of a List.
There are others.
Here's an example of how one could use an instance of class ArrayList.
It will run only under JDK 1.2 and beyond:
package examples;
import java.util.ArrayList;
import java.util.Iterator;
public class ArrayListExample
{
public static void main(String[] args)
{
ArrayList list = new ArrayList();
list.add("Mary");
list.add("Frank");
list.add("Joe");
list.add("Sylvia");
list.add("Vanessa");
for (int i = 0; i < list.size(); i++)
{
String name = (String) list.get(i); // Note required cast
System.out.println(i + ": " + name);
}
for (Iterator iter = list.iterator(); iter.hasNext(); )
{
String name = (String) iter.next(); // Note required cast
System.out.println(name);
}
}
}
|
which produces the output:
0: Mary
1: Frank
2: Joe
3: Sylvia
4: Vanessa
Mary
Frank
Joe
Sylvia
Vanessa
The output is exactly the same as for the earlier Vector/Enumeration
example.
Again, note the two ways of obtaining the elements of the list:
- Access each element by its index, using the get(int index)
method
- Access each element through an Iterator
object, supplied by the ArrayList. (Remember,
Iterator is an interface.)
This is the "new style".
|