java/lang/Stack

Archie Cobbs kaffe@rufus.w3.org
Sat, 22 Aug 1998 14:53:00 -0700 (PDT)


A quick look at java/lang/Stack.java reveals that it does indeed contain
a bug, in that search() returns the wrong value.

A fixed & cleaned up version is included below.

References: 

      http://java.sun.com/products/jdk/1.2/docs/api/java/util/Stack.html
      http://java.sun.com/products/jdk/1.2/docs/api/java/util/Vector.html

-Archie

___________________________________________________________________________
Archie Cobbs   *   Whistle Communications, Inc.  *   http://www.whistle.com

package java.util;

/*
 * Java core library component.
 *
 * Copyright (c) 1997, 1998
 *      Transvirtual Technologies, Inc.  All rights reserved.
 *
 * See the file "license.terms" for information on usage and redistribution
 * of this file.
 */
public class Stack
  extends Vector
{

public Stack() {
}

public boolean empty() {
	return isEmpty();
}

public Object peek() throws EmptyStackException {
	try {
		return elementAt(size() - 1);
	} catch (ArrayIndexOutOfBoundsException _) {
		throw new EmptyStackException();
	}
}

public Object pop() throws EmptyStackException {
	Object peeked = peek();

	removeElementAt(size() - 1);
	return peeked;
}

public Object push(Object item) {
	addElement(item);
	return item;
}

public int search(Object o) {
	int index = lastIndexOf(o);

	if (index == -1) {
		return -1;
	}
	return size() - index;
}
}