Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

stack generic

 
Justin Fox
Ranch Hand
Posts: 802
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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..

Justin
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Allan Jacobs
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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;
}
}

}
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic