繁体   English   中英

Java 中的通用数组方法类

[英]Generic Array Method Class in Java

我一直在尝试将这个通用的 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;
      }
   }
}

注意:您必须首先像注释中提到的那样更正您的代码。

  • 推荐使用官方 Stack 类的 name 方法,所以有 5 个方法: empty() peek() pop() push(E item) search(Object o)

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

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

peek()方法的代码:

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

push(E o)方法的代码:

 public E push(E o) {
  list[currentSize]=o;
  currentSize++;
    return o;

}

pop()方法的代码,此方法必须抛出EmptyStackException - 如果此堆栈为空:

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

  }

empty()方法的代码:

public boolean empty() {
  if (currentSize > 0) {
    return false;
  }
  else {
      return true;
    }
   }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM