【问题标题】:I'm not sure how to make this stack implementation dynamic我不确定如何使这个堆栈实现动态化
【发布时间】:2014-02-26 11:41:48
【问题描述】:

首先,如果这是一个非常明显的问题,或者我没有正确看待它,我深表歉意。 我被指示“将堆栈扩展为动态”。我已获得有关如何执行此操作的具体说明,即:

  • 创建一个两倍于当前数组大小的新数组 tmp

  • 将当前数组中的所有元素(讲义中称为 S)复制到 tmp 中

  • 设置 S = tmp;

应该执行此操作的代码块将被放入 push() 方法中,替换异常抛出部分。

问题是,我不知道我应该使用什么样的数组(泛型是最近才介绍给我的,我并没有像我想的那样理解它们)。 有什么明显的我遗漏了,还是我没有正确理解这一点?

这段代码的大部分不是我写的,只有 pop()、push() 和 top() 方法。

public class ArrayStack<E> implements Stack<E> {
private E[] S;
private int top;
private int capacity;

private static int DEFAULT_SIZE = 100;

public ArrayStack(int size){
    capacity = size;
    S = (E[]) new Object[size];
    top = -1;
}

public ArrayStack(){
    this(DEFAULT_SIZE);
}


public E pop() throws StackException{
    if(isEmpty())
        throw new StackException("stack is empty");
    return S[top--];
}



public void push(E e) throws StackException{
    if (size() == capacity)
        throw new StackException("Stack is full");
    S[++top] = e;
}



public E top() throws StackException{
    if(isEmpty())
        throw new StackException("Stack is empty");
    return S[top];



}

【问题讨论】:

  • 在这种情况下,“动态”是什么意思?这是否意味着允许底层数组在满/需要时扩展大小?
  • 我认为基本上我被要求做的是每当有东西被压入堆栈时将底层数组的大小加倍,然后将当前数组的内容转移到新数组中 -这是一个可怕的解决方案,但我只是 Java 的初学者。
  • 这不是一个糟糕的解决方案——它是大多数有序数据结构的工作方式。当内部数组已满时,它会扩展一定的因子(双倍也可以),然后将旧数据复制到新数组中。
  • 哦,我只是认为这不是一个好方法,因为(据我的理解)每次将某些东西压入堆栈时,都会为数组分配两倍的内存。谢谢!

标签: java arrays generics stack


【解决方案1】:

查看您的代码,该数组似乎应该是 E 对象。

使用 Java 泛型,您可以使用 (E[]) new Object[2 * initial_size] 创建此数组

指令要你看push下面的代码段

if (size() == capacity)
        throw new StackException("Stack is full");

不要放弃太多,因为这是一项任务

if (size() == capacity)
       Make a new array tmp of twice the size of the current array
       Copy all elements the current array (called S in the lecture notes) into tmp
       S = tmp;

【讨论】:

  • 感谢您的回答-我尝试在 push() 开始后使用tmp = new E[size*2]; 创建一个新的 E 对象数组,但是 Eclipse 给了我 3 个错误-它无法创建E 的通用数组,并且 tmp 和 size 无法解析为变量。正确的语法是什么?
  • @Chewy (E[]) new Object[size*2]
  • 我很抱歉,但我还是没听懂 - 当我尝试使用 (E[]) new Object[size*2] 时,我遇到了很多错误。我知道这里有一些很明显的东西我一定错过了,但我不知道它是什么。
  • 我相信您的情况下的“大小”可能是“私有 int 容量”,因为这是您的类字段的名称。但是,请务必将字段的值更新为创建新数组时的 2 倍。
  • @Chewy:你应该得到未经检查的演员表警告,而不是错误
猜你喜欢
  • 2012-01-18
  • 2016-03-15
  • 2014-04-20
  • 2014-12-14
  • 2010-09-22
  • 1970-01-01
  • 2019-04-29
  • 2012-09-02
  • 2017-10-20
相关资源
最近更新 更多