1

i'm creating the method toArray in the code below, getting cannot find symbol error in calling both pop() and push() methods inside toArray. Why?

   public void push(Comparable x)
   {
      arr[size++] = x;
   }

   public Object pop() throws EmptyStackException
   {
      return arr[size--];
   }

   public Comparable[] toArray() 
   {
      Comparable[] newarr = new Comparable[size];
      for(int i = 0; i < size; i++)
      {
         newarr[i] = arr.pop();
      }
      for(int i = size; i > 0; i--)
      {
         arr.push(newarr[i-1]);
      }
      return newarr;
   }

2 Answers2

2

You are calling arr.push() and arr.pop(). However the push and pop are methods in your class. Just call push(arr); and pop without the arr prefix.

pczeus
  • 7,709
  • 4
  • 36
  • 51
  • Is it correct to think that those methods already refers to "this" and so arr. is incorrect? – Andrea Ferlat Feb 20 '16 at 01:00
  • 1
    Correct. Because you are in the context of your Class, just calling `push()` is equivalent to calling `this.push()`. Trying to invoke `arr.push()` would mean you are attempting to call a method on `arr`, which doesn't exist. – pczeus Feb 20 '16 at 01:05
0

Looking at your other uses of arr, it looks like it has been defined as an array of objects. Java arrays by themselves do not have access to push and pop methods.

If you're looking to access the push and pop methods you've created, use

pop();
push(newarr[i-1]);

Rather than:

arr.pop();
arr.push(newarr[i-1]);
Dylan Wheeler
  • 6,928
  • 14
  • 56
  • 80