Reputation: 83
I'm trying to push Integer onto a generic array. Here's my code:
import java.lang.reflect.Array;
public class StackMain
{
public void main (String[]args)
{
Integer[] oneStack = null;
Integer a = new Integer("1");
oneStack = (Integer[])Array.newInstance(Integer.class, 10);
push(a, oneStack);
}
}
public class Stack<T>
{
private T[] oneStack;
public void push(T item, T[] array)
{
array[1] = item; //dummy method for testing
}
}
But push(a, oneStack)
gives me a "cannot find symbol" error for some reason. Should I use Integer[]
instead of T[]
? I thought that Integer was a generic ...
Upvotes: 1
Views: 774
Reputation: 1500695
push(a, oneStack); gives me cannot find symbol for some reason.
Yes, because you're trying to call it in StackMain
, and it only exists in Stack<T>
. You need to create a Stack<Integer>
in order to call it:
Stack<Integer> stack = new Stack<Integer>();
stack.push(a, oneStack);
If you want to allow it to be called without creating an instance, it needs to be a static
method. (I'm assuming that in reality, there's more code.)
(If you're very new to Java, I'd suggest concentrating on the really core stuff such as invoking methods and creating objects before you worry about generics. You'll need to tackle them soon, but if you try to learn about them while you're still getting to grips with the very basics, it'll slow you down in the long run.)
Upvotes: 5
Reputation: 528
The method push is not visible to StackMain class (as it is in Stack class) unless you create an instance of Stack and then refer it. Either you should localize this method to StackMain class or create an instance of Stack class.
Upvotes: 0
Reputation: 850
You need to create an instance of your stack object before calling the push(...) method on it
Upvotes: 0