Java中的通用数组方法类

时间:2015-11-28 21:03:34

标签: java arrays generics

我一直在努力将这个通用的arraylist类变成一个数组,但我还是无法让它工作。我在push()和pop()方法中遇到了障碍。任何帮助表示赞赏。

这是原始课程:

public class GenericStack<E> {
  private java.util.ArrayList<E> list = new java.util.ArrayList<E>();

  public int getSize() {
    return list.size();
  }

  public E peek() {
    return list.get(getSize() - 1);
  }

  public E push(E o) {
    list.add(o);
    return o;
  }

  public E pop() {
    E o = list.get(getSize() - 1);
    list.remove(getSize() - 1);
    return o;
  }

  public boolean isEmpty() {
    return list.isEmpty();
  }
}

到目前为止,这是我的修订课程:

public class GenericStack<E> {
    public static int size = 16;
    @SuppressWarnings("unchecked")
    private E[] list = (E[])new Object[size];

  public void add(int index, E e) {
      ensureCapacity();

      for (int i = size - 1; i >= index; i--) {
          list[i + 1] = list[i];

      list[index] = e;

      size++;   
    }
  }
  public int getLength() {
    return list.length;
  }

  public E peek() {
      E o = null;
      o = list[0];
      return o;
  }
  public E push(E o) {
      ensureCapacity();
      list.append(o);
        size++;
        return o;
  }
  public E pop() {
      E o = null;
      for (int i = 0; i > list.length; i++) {
          o = list[i - 1];
    }
        list[list.length - 1] = null;
        size--;
        return o;
      }
  private void ensureCapacity() {
      if (size >= list.length) {
        @SuppressWarnings("unchecked")
        E[] newlist = (E[])(new Object[size * 2 + 1]);
          System.arraycopy(list, 0, newlist, 0, size);
          list = newlist;
      }
  }
  public boolean isEmpty() {
      if (list.length > 0) {
        return false;
      }
      else {
          return true;
      }
   }
}

1 个答案:

答案 0 :(得分:0)

注意:您必须首先更正您在评论中提到的代码。

  • 建议使用类似官方Stack类的名称方法,因此有5种方法:empty() peek() pop() push(E item) {{ 1}}。

  • 您应该将数组的初始大小声明为常量,将其他变量声明为当前大小,并且所有属性都应该 search(Object o)

    private

peek()方法的代码:

private final int MAX_SIZE = 16;
private int currentSize=0;

推(E o)方法的代码:

public E peek() {
      E o = null;
      o = list[currentSize-1];
      return o;
}

}

此方法必须抛出{strong> pop()方法的代码 public E push(E o) { list[currentSize]=o; currentSize++; return o; - 如果此堆栈为空:

EmptyStackException

empty()方法的代码:

 public E pop() {
  E o = null;
  if(currentSize>0){
      o=list[currentSize - 1];
    list[currentSize - 1] = null;
    currentSize--;
    return o;
  }else{
      throw new EmptyStackException();
  }

  }