toArray方法总结

toArray方法总结toArray 方法涉及 java 的泛型 反射 数组的协变 jvm 等知识 Java 标准库中 Collection 接口定义了 toArray 方法 如果传入参数为空 则返回 Object 数组 如果传入参数为 T 则返回参数为传入参数的运行时类型 以下是 ArrayList 的实现 略去无关内容 public class ArrayList extends AbstractList

toArray方法涉及java的泛型,反射,数组的协变,jvm等知识。

Java标准库中Collection接口定义了toArray方法,如果传入参数为空,则返回Object[]数组,如果传入参数为T[],则返回参数为传入参数的运行时类型。以下是ArrayList的实现:

// 略去无关内容
public class ArrayList extends AbstractList
implements List, RandomAccess, Cloneable, java.io.Serializable{
@SuppressWarnings("unchecked")
public T[] toArray(T[] a) {
if (a.length < size)
// Make a new array of a's runtime type, but my contents:
return (T[]) Arrays.copyOf(elementData, size, a.getClass());
System.arraycopy(elementData, 0, a, 0, size);
if (a.length > size)
a[size] = null;
return a;
}

public Object[] toArray() {
return Arrays.copyOf(elementData, size);
}
}

1. 传入的静态参数T为编译器提供了编译器检查,如果类型不匹配,则编译不通过。

如test1所示,Byd[] 不能接受静态返回类型Brand[],除非作类型强转,才可以编译通过,但是会报运行时类型转换异常。这个异常非常有意思,虽然方法返回的数组类型为Brand[],并且其中的每个元素都为Byd,但是Brand[]类型不能强转为Byd[]类型。根本原因是JVM的限制,即不能对运行时数组类型进行强转。如test3所示,cmps的静态类型是Comparable[],运行时类型是Integer[],运行时类型不能转化。

类型转换中向上转型是支持的(转型为父类或接口),向下转型必须进行类型强转,可能报运行时异常。java中数组支持协变,即Byd[]是Brand[]的子类,可以用Brand[]类型接收Byd[]对象,如test4所示。

test6也很有意思,虽然List转化为了Brand[],编译通过,但是由于传入的Byd[]为brands1的运行时类型,在往实际的Byd[]中存放Brand的过程中,会报ArrayStoreException异常,由于Java支持数组协变,这种运行时异常无法在编译期检查出来。最简单的例子见如下源码注释:

此时在运行时抛出了数组存储异常,因为数组的实际类型为String[],虚拟机运行时进行类型检查发现类型不匹配就抛出此异常。

数组对象的底层数据存储如上图所示,对象头中Mark Word存储hashCode和内存回收、并发相关信息,Klass Word为类型指针,存储类型不匹配抛出ArrayStoreException,array length为数组长度,数组越界抛出ArrayIndexOutOfBoundsException。

interface Brand {
int getId();
String getBrandName();
}

@Data
@AllArgsConstructor
class Byd implements Brand {
int id;
String brandName;
Integer speed;
}

@Data
@AllArgsConstructor
class Tesla implements Brand {
int id;
String brandName;
}

public class ArraysTest {
@Test
public void test1() {
List byds = new ArrayList<>();
byds.add(new Byd(1, "唐", 100));
byds.add(new Byd(2, "宋", 120));
// Byd[] byds1 = byds.toArray(new Brand[0]);
// 传入参数类型Brand[]和返回参数类型不匹配, 不能编译通过

Byd[] byds1 = (Byd[]) byds.toArray(new Brand[0]);
// 编译通过,报运行时异常:
// java.lang.ClassCastException: [Lcom.dahua.Brand; cannot be cast to [Lcom.dahua.Byd;
}

@Test
public void test2() {
List byds = new ArrayList<>();
byds.add(new Byd(1, "唐", 100));
byds.add(new Byd(2, "宋", 120));
Brand[] brands = byds.toArray(new Byd[0]);
System.out.println(Arrays.toString(brands));
// 输出:
// [Byd(id=1, brandName=唐, speed=100), Byd(id=2, brandName=宋, speed=120)]
}

@Test
public void test3() {
Integer[] ints = new Integer[3];
Arrays.setAll(ints, x -> x+1);
Comparable[] cmps = (Comparable[]) ints;
System.out.println(cmps.getClass().getComponentType());
// 输出:
// class java.lang.Integer
}

@Test
public void test4() {
List byds = new ArrayList<>();
byds.add(new Byd(1, "唐", 100));
byds.add(new Byd(2, "宋", 120));
Brand[] brands = byds.toArray(new Byd[0]);
System.out.println(brands.getClass().getComponentType());
// 输出:
// class com.dahua.Byd
}

@Test
public void test5() {
List brands = new ArrayList<>();
brands.add(new Byd(1, "唐", 100));
brands.add(new Byd(2, "宋", 120));
Brand[] brands1 = brands.toArray(new Byd[0]);
System.out.println(brands1.getClass().getComponentType());
// 输出:
// class com.dahua.Byd
}

@Test
public void test6() {
List brands = new ArrayList<>();
brands.add(new Byd(1, "唐", 100));
brands.add(new Byd(2, "宋", 120));
brands.add(new Tesla(3, "model S"));
Brand[] brands1 = brands.toArray(new Byd[0]);
// 编译通过, 但是运行时异常:
// java.lang.ArrayStoreException
}
}

2. 如果toArray方法传入的数组长度大于等于list的size,只将size后一个位置置空。由于ArrayList::toArray方法通常传入长度为0的数组,调用了Arrys::copyOf方法,下面来看此方法。

public class Arrays {    
public static T[] copyOf(U[] original, int newLength, Class newType) {
@SuppressWarnings("unchecked")
T[] copy = ((Object)newType == (Object)Object[].class)
? (T[]) new Object[newLength]
: (T[]) Array.newInstance(newType.getComponentType(), newLength);
System.arraycopy(original, 0, copy, 0,
Math.min(original.length, newLength));
return copy;
}
}

首先创建copy对象,其类型只能在运行时指定,Array::newInstance可以在运行时创建数组,动态指定类型。

泛型T U可以用作静态类型检查,如test7所示,传入的Double[].class,其返回值可以由Comparable[]接收,只要newType代表的静态类型为T[]的子类即可,Double[]是Comparable[]的子类,虽然静态类型检查通过,但是运行期异常报出。

如果传入raw类型(不带泛型的Class),依然可以通过编译,这是java为了前向兼容非泛型类型。此时返回类型为Object[],实际上此方法的字节码返回的也是Object[]。建议使用带泛型的形式。

对于不安全的类型转换编译器会报unchecked 警告,表示编译器无法做类型检查。对于确定安全的方法,使用@SuppressWarnings关闭。对于编译器报unchecked警告需要提高警惕,此处极有可能遇到bug问题。

System.arraycopy为native方法,在内存中对数组进行复制,效率更高。

    @Test
public void test7() {
Integer[] ints = new Integer[10];
Arrays.setAll(ints, x -> x+1);
// Comparable[] comparables = Arrays.copyOf(ints, 5, Double[].class);
// 编译通过,运行时异常

Class clazz = Object[].class;
System.out.println(clazz);

Object[] arr = Arrays.copyOf(ints, 4, clazz);
System.out.println(Arrays.toString(arr));

// clazz = Number[].class;
// Number[] objects = Arrays.copyOf(ints, 5, clazz);
// 无法编译,类型不匹配
}

通过以上分析,对于LinkedList的分析就简单了。

// 遍历复制
public Object[] toArray() {
Object[] result = new Object[size];
int i = 0;
for (Node x = first; x != null; x = x.next)
result[i++] = x.item;
return result;
}


// 运行时创建数组,遍历复制
@SuppressWarnings("unchecked")
public T[] toArray(T[] a) {
if (a.length < size)
a = (T[])java.lang.reflect.Array.newInstance(
a.getClass().getComponentType(), size);
int i = 0;
Object[] result = a;
for (Node x = first; x != null; x = x.next)
result[i++] = x.item;

if (a.length > size)
a[size] = null;

return a;
}

// 注意:toArray方法没有对List泛型类型E和数组类型进行校验,所以便有如下测试结果。

// 可以通过编译,运行通过
@Test
public void test9() {
List list = new LinkedList<>();
Double[] list2 = list.toArray(new Double[0]);
for (Double d : list2) {
System.out.println(d);
}
}

// 编译通过,运行异常
@Test
public void test10() {
List list = new LinkedList<>();
list.add(1);
Double[] list2 = list.toArray(new Double[0]);
// java.lang.ArrayStoreException: java.lang.Integer
for (Double d : list2) {
System.out.println(d);
}
}

总结:

1. 由于数组编译时需要“物化”类型,而泛型在Java运行时已经擦除为Object、上界(extends)、上界(extends),不能确定具体的类型,编译器不通过。如果需要在运行时确定数组类型并创建数组,需要调用Array.newInstance方法,传入泛型类型参数。

2. 使用时尽量带上泛型参数,便于编译期检查类型。

3. 注意@SuppressWarnings(“unchecked”)方法使用时可能会有运行时异常,应该小心使用此类方法。

编程小号
上一篇 2025-01-29 17:30
下一篇 2025-01-25 21:46

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/hz/118664.html