有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何将对象[]转换为特定类型数组

我认为我无法转换以下内容:

List<B> c = new ArrayList<B>();
c.add(***);
object[] a = c.toArray();
B[] b = (B[])a; //How to cast a back to B[]?

如何在Java中实现这一点


共 (4) 个答案

  1. # 1 楼答案

    你不能通过石膏来做这件事。你必须复制数据

    B[] b = new B[a.length];
    for (int i=0; i<a.length; i++){
       b[i] = (B)a[i];
    }
    
  2. # 2 楼答案

    其他答案显示了如果您真的需要转换Object[]时该怎么做-但是有一个更好的方法。将代码更改为以以下内容开头:

    List<B> c = new ArrayList<B>();
    c.add(***);
    B[] b = c.toArray(new B[c.size()]);
    

    或:

    List<B> c = new ArrayList<B>();
    c.add(***);
    B[] b = c.toArray(new B[0]);
    
  3. # 3 楼答案

    @Jon Skeet的answer是正确的,但以下是Intellij IDEA检查信息中的一些上下文:

    There are two styles to convert a collection to an array: either using a pre-sized array (like c.toArray(new String[c.size()])) or using an empty array (like c.toArray(new String[0]).

    In older Java versions using pre-sized array was recommended, as the reflection call which is necessary to create an array of proper size was quite slow. However since late updates of OpenJDK 6 this call was intrinsified, making the performance of the empty array version the same and sometimes even better, compared to the pre-sized version. Also passing pre-sized array is dangerous for a concurrent or synchronized collection as a data race is possible between the size and toArray call which may result in extra nulls at the end of the array, if the collection was concurrently shrunk during the operation.

  4. # 4 楼答案

    如果a的每个元素都是B类型,则有两个选项(如果不是,则需要首先解释发生了什么):

    B[] bArray;
    if(a instanceof B[]){
        // a is actually of type B[], so we'll cast it
        bArray = (B[]) a;
    }else{
        // a is of type Object[], so we'll create a new array and copy the values
        bArray = Array.newInstance(B.class, a.length);
        System.arraycopy(a, 0, bArray, 0, a.length);
    }
    

    此外,这仅在B是实类型而不是泛型参数时才有效