Hi,
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)
{
if(isNotFull())
{
top++;
array[top] = obj;
}
else
{
stackError(errormsg.OVERFLOW);
}
}
public T pop()
{
if( isNotEmpty() )
return (T)array[top--];
else
{ stackError( errormsg.UNDERFLOW ); }
return null;
}
public T peek()
{
if(isNotEmpty())
return (T)array[top];
else
stackError(errormsg.UNDERFLOW);
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;
while(front>=0)
System.out.print(array[front--] + " ");
System.out.println();
}
public int Size()
{
return top+1;
}
public void stackError(errormsg msg)
{
switch (msg)
{
case UNDERFLOW:
System.out.println("stack is empty!");
break;
case OVERFLOW:
System.out.println("stack is full!");
break;
}
}
}