【问题标题】:How to convert Generic Arraylist into Array in Java?如何在 Java 中将 Generic Arraylist 转换为 Array?
【发布时间】:2016-03-01 05:37:07
【问题描述】:

我需要更改此程序以使用数组而不是数组列表。显然我需要创建一个对象数组并将其转换为 E[] 但我不明白如何做到这一点。任何帮助表示赞赏。

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();
  }
}

【问题讨论】:

标签: java arrays generics


【解决方案1】:

代替:

private java.util.ArrayList<E> list = new java.util.ArrayList<E>();

使用:

private Object[] array = new Object[];

而当你必须返回某个值时,将其强制转换为 E。例如:

public E get(int i) {
    return (E) array[i];
}

这是必要的,因为 Java 不允许您创建泛型类型的数组。

【讨论】:

    【解决方案2】:

    您可以使用以下命令来创建数组。

    private E[] arr;
    private int index;
    
    public void initialize() {
        arr = (E[]) new Object[100];
        index = 0;
    }
    
    public E push(E o) {
        try {
            arr[index++] = o;
        } catch (Exception e) {
            System.out.println("Array not enough..");
        }
        return o;
    }
    

    使用它,您也可以实现其他方法。 index 可用于计算堆栈的大小。

    在上面的示例中,超出数组边界时会打印错误。相反,您可以在index == arr.length - 1 时将数组复制到另一个变量中。您可以使用以下函数来复制数组..

    private void copyArray() {
        E[] tem = (E[]) new Object[arr.length + 100];
        System.arraycopy(arr, 0, tem, 0, arr.length);
        arr = tem;
    }
    

    【讨论】:

      【解决方案3】:

      你可以像这样初始化一个通用数组:

      E[] stack = (E[])new Object[size];
      

      我在另一个问题中找到了一个通用堆栈示例:Generic Stack Array

      【讨论】:

      • 虽然这段代码可以编译并且对于这种情况是有效的,但它有一个警告。 stack 变量在运行时不会像 E 的数组那样运行 - 它不会为原始对象抛出 ArrayStoreException。本质上,Object[] 转换为 E[] 不是 E[]。恕我直言,最好的解决方案是在内部保持原始Object[],而不是公开与E 相关的接口(如Phoenix 建议的那样)
      【解决方案4】:

      其实你想做的是一个使用数组的栈实现。

      使用数组实现通用堆栈

      public class GenericStack<E> {
          private int index;
          private E[] array;
      
          public GenericStack(int size) {
              array = (E[]) new Object[size];
              index = 0;
          }
      
          public int getSize() {
              return index;
          }
      
          public int getCapacity() {
              return array.length;
          }
      
          public E peek() {
              return array[index-1];
          }
      
          // push MUST be void, it only pushes the value into the stack
          public void push(E o) {
              array[index++] = o;
          }
      
      
          public E pop() {
              E o = array[index-1];
              index--;
      
              return o;
          }
      
          public boolean isEmpty() {
              return index == 0 ? true : false; 
          }
      }
      

      测试代码

      public class TestGenericStack {
      
          public static void main(String[] args) {
              GenericStack<Integer> genStack = new GenericStack<Integer>(10);
      
              // test size
              System.out.println("Size of the Stack  : " + genStack.getSize());
      
              // test isEmpty()
              System.out.println("Stack isEmpty      : " + genStack.isEmpty());
      
      
              System.out.println("*** Stack push operations ***");
      
              // test push
              genStack.push(new Integer(10));
              genStack.push(new Integer(20));
              genStack.push(new Integer(30));
              genStack.push(new Integer(15));
              genStack.push(new Integer(99));
      
      
      
              // test isEmpty()
              System.out.println("Stack isEmpty      : " + genStack.isEmpty());
      
              // test peek
              System.out.println("Top of the Stack   : " + genStack.peek());
      
              // test size
              System.out.println("Size of the Stack  : " + genStack.getSize());
      
              // test pop
              System.out.println("Pop from the Stack : " + genStack.pop());
      
              // test peek
              System.out.println("Top of the Stack   : " + genStack.peek());
      
              // test size
              System.out.println("Size of the Stack  : " + genStack.getSize());
          }
      
      }
      

      控制台输出

      Size of the Stack  : 0
      Stack isEmpty      : true
      *** Stack push operations ***
      Stack isEmpty      : false
      Top of the Stack   : 99
      Size of the Stack  : 5
      Pop from the Stack : 99
      Top of the Stack   : 15
      Size of the Stack  : 4
      

      【讨论】:

        【解决方案5】:

        数组不能使用泛型类型,因为它需要为该类型分配内存。因此,它需要事先知道它是哪种类型。您可以使用 newInstance() 方法将使用 ArrayList 实现的堆栈转换为数组。代码将如下所示。

        public E[] toArray() {
        
            if (size == 0)
                return null;
        
            E temp = list.get(0);
            E[] stackArray = (E[]) Array.newInstance(temp.getClass(), size);
            for (int i = 0; i < list.size(); i++) {
                stackArray[i] = list.get(i);
            }
            return (E[]) stackArray;
        }
        

        【讨论】:

          【解决方案6】:

          泛型在编译中被删除,因此Helper.toArray 将被编译为返回Object[]

          对于这种特殊情况,我建议您使用 List.toArray(E[])。

          List<E> list = new ArrayList<E>();
               list.add(...);
               list.add(...);
          
          T[]array = list.toArray(new E[list.size()]);
          

          【讨论】:

          • 因为 Java 泛型在 Java 8 中没有具体化,所以当您尝试创建参数化泛型类型的数组时会导致编译器错误。您的代码将无法编译。
          猜你喜欢
          • 2019-04-10
          • 2012-04-13
          • 2016-05-11
          • 2017-06-02
          • 2012-03-16
          • 2018-04-29
          • 2020-04-26
          • 1970-01-01
          • 2016-02-01
          相关资源
          最近更新 更多