0

I am attempting to use a stack to put objects in a stack. I have a Pixel class that has a simple getX function that returns a variable defined in the constructor. When I use the stack.peek().getX(); it says that it cannot find the symbol for .getX();

Stack stack = new Stack();
Pixel first = new Pixel(colorX,colorY);

stack.push(first);

int x = stack.peek().getX();

Am I using the peek function wrong? Or do I have my Pixel class setup incorrectly?

public class Pixel {
private int x, y , count = 0;

Pixel(int x_in, int y_in)
{
    x = x_in; 
    y = y_in;
}

public int getX(){return x;}
public int getY(){return y;}

2 Answers2

1

It is because you are using a raw Stack, instead of Stack<Pixel> that you get this error. A raw stack is essentially equivalent to Stack<Object>, so when you call peek() it returns Object and not Pixel.

Even though the runtime type may be Pixel, method resolution happens at compile time and Object has no getX() method.

Jim Garrison
  • 85,615
  • 20
  • 155
  • 190
0

You defined your stack with Stack stack = new Stack();, but the definition of the stack class has a parameter type Stack. By not declaring the type, as is possible due to Java not always having had the generics, you basically wrote Stack<?>, so the compiler doesn't know which methods the returned value will have.

How to solve? Declare your stack as Stack<Pixel> stack = new Stack<>();

M. le Rutte
  • 3,525
  • 3
  • 18
  • 31