Program 21.2: A char stack

This technique is even more useful when you want to fill a data structure with a primitive data type like int or char. However because you need to replace the methods rather than override them, it takes a little more work. Rather than subclassing java.util.Stack you embed a java.util.Stack in the class and handle the conversions between primitive data types and type wrapper classes in the individual methods. It's messy, but once you've done it the rest of your code doesn't need to worry about how you've done it, just that it works. Code reusability is, after all, one of the advantages of object oriented programming. Program 21.2 demonstrates this with a stack class for chars.

import java.util.Stack;

public class charStack {

  private Stack theStack;

  charStack() {
    theStack = new Stack();

  public char peek() {
    Character temp = (Character) theStack.peek();
    return temp.charValue();

  public void push(char c) {
    theStack.push(new Character(c));

  public char pop() {
    Char temp = (Character) theStack.pop();
    return temp.charValue();
  public boolean empty() {  
    return theStack.empty();

Finally you should note that this technique is useful for all the java.util data structures that expect objects, not just for Stacks.

Copyright 1996 Elliotte Rusty Harold
This Chapter