1

我在下面的代码中创建方法 toArray,在调用 toArray 中的 pop() 和 push() 方法时出现找不到符号错误。为什么?

   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;
   }
4

2 回答 2

2

您正在呼叫arr.push()arr.pop()。但是 push 和 pop 是您类中的方法。只需调用push(arr);并且pop没有 arr 前缀。

于 2016-02-20T00:37:56.187 回答
0

查看您对 的其他用途arr,看起来它已被定义为对象数组。Java 数组本身无法访问 push 和 pop 方法。

如果您希望访问您创建的push和方法,请使用pop

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

而不是:

arr.pop();
arr.push(newarr[i-1]);
于 2016-02-20T00:36:29.663 回答