File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes stack generic Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "stack generic " Watch "stack generic " New topic

stack generic

Justin Fox
Ranch Hand

Joined: Jan 24, 2006
Posts: 802
ok here is my code,

ok, im getting an error, here it is...

I looked at a Stack Generic online, and this is the way they did their's,
and im pretty sure thats how we did it last year in class, but i can't

get it to go away..


You down with OOP? Yeah you know me!
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

The syntax there is OK. I would guess the problem is you're using a pre-Java 5 compiler. Generics were introduced in Java 5 (JDK 1.5), and anything older will just report syntax errors.

[Jess in Action][AskingGoodQuestions]
Allan Jacobs

Joined: Aug 28, 2006
Posts: 15

The example Stack<T> will not compile when you use a Java 5 compiler.

First, there are some shallow problems in the pop and peek methods. Their return type is 'int' and it's not guaranteed that a 'T' will unwrap to an int. Only if T is a subtype of java.lang.Integer will this be true.

Second, the type parameter is used as if the compiler could use it as a parameterized constructor name. This is not the case. The type parameters are merely used to enable the compiler to do type checking and have no impact on the bytecode that is generated. The problem is in the line that reads 'array = new T[number]'.

The code that follows compiles, the class that it generates can be
instantiated, and it seems to execute correctly, too.

package scjp.generic;

class Stack <T>
public int count = 0, size = 0, top = -1;
public String result;
public Object[] array;

public enum errormsg{UNDERFLOW, OVERFLOW};
int front = 0;

public Stack(int number)
array = new Object [number];

public void push(T obj)
array[top] = obj;


public T pop()
if( isNotEmpty() )
return (T)array[top--];
{ stackError( errormsg.UNDERFLOW ); }
return null;

public T peek()
return (T)array[top];
return null;

public boolean isNotFull()
return top<array.length-1;

public boolean isNotEmpty()
return top >= 0;

public void dump()

System.out.print("\t\t\t top: " + top + " Contents: " );
front = top;

System.out.print(array[front--] + " ");



public int Size()
return top+1;

public void stackError(errormsg msg)
switch (msg)
System.out.println("stack is empty!");
System.out.println("stack is full!");

I agree. Here's the link:
subject: stack generic
It's not a secret anymore!