SE450: Taxonomy: Collection Classes [62/63] |
A collection may hold references to many other objects.
Usually the objects are of some uniform type, eg, a list of dogs, a set of colors.
The java.util provides several collection classes. (See the java tutorial.)
We may implement our own collections. Usually these make use of the java.util classes.
In the following example, IntegerStack delgates most of its responsibilities to List.
file:IntegerStack.java [source] [doc-public] [doc-private]
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
package basics.collection; import java.util.List; import java.util.ArrayList; import java.util.EmptyStackException; final public class IntegerStack { final private List<Integer> l; public IntegerStack() { l = new ArrayList<Integer>(); } public boolean isEmpty() { return l.isEmpty(); } public void push(Integer x) { if (x == null) throw new IllegalArgumentException(); l.add(x); } public Integer pop() { if (l.isEmpty()) throw new EmptyStackException(); return l.remove(l.size()-1); } }