1

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 ...

3
  • What does your Stack<T>.push intend to do? It isn't clear to me whether you want to push item to array or oneStack. Commented Jun 7, 2013 at 6:01
  • I would work on simplifying your code. I suspect it doesn't need to be doing half the things your code is doing. Commented Jun 7, 2013 at 6:17
  • i need to use an array that implements the stack ADT. Commented Jun 7, 2013 at 8:34

3 Answers 3

5

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.)

Sign up to request clarification or add additional context in comments.

3 Comments

does stack refer to a stack object or it's just used to access the method in the stack class?
ah thanks it's working, it seems that i needed to instantiate a stack object even though i didn't have any constructor.
@david: You do have a constructor: the default public parameterless constructor that the compiler provides for you if you don't specify any constructors explicitly.
0

You need to create an instance of your stack object before calling the push(...) method on it

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.