gpt4 book ai didi

java - 为什么 Arrays.asList(...).toArray().getClass() 在 JDK 8 和 9 中给出不同的结果?

转载 作者:IT老高 更新时间:2023-10-28 20:40:11 24 4
gpt4 key购买 nike

为什么以下条件在 JDK 8 中返回 true,而在 JDK 9 中返回 false

String[].class == Arrays.asList("a", "b").toArray().getClass()

最佳答案

asList 返回的List 类型是Arrays$ArrayList .该类的 JDK 8 中的 toArray 方法是:

@Override
public Object[] toArray() {
return a.clone();
}

但在 JDK 9+ 中是:

@Override
public Object[] toArray() {
return Arrays.copyOf(a, a.length, Object[].class);
}

在这两种情况下,String[] 都被传递给 asList,但在 JDK 8 的情况下,它被克隆,保留了它的数组类型(String[ ]),而在 JDK 9+ 中,它是使用 Arrays.copyOf 和显式的新数组类型 Object[] 复制的。

这种差异意味着在 JDK 8 中 Arrays.asList("a", "b").toArray().getClass() 返回 String[] 而在JDK 9+ 它返回 Object[],因此在 JDK 9+ 中,您的表达式将评估为 false

这个变化的原因来自JDK-6260652动机:

The Collection documentation claims that

collection.toArray()

is "identical in function" to

collection.toArray(new Object[0]);

However, the implementation of Arrays.asList does not follow this: If created with an array of a subtype (e.g. String[]), its toArray() will return an array of the same type (because it use clone()) instead of an Object[].

If one later tries to store non-Strings (or whatever) in that array, an ArrayStoreException is thrown.

因此进行此更改是为了修复以前的行为。


如果这对您来说是个问题,相关的 release note将此作为解决方法:

If this problem occurs, rewrite the code to use the one-arg form toArray(T[]), and provide an instance of the desired array type. This will also eliminate the need for a cast.

String[] array = list.toArray(new String[0]);

关于java - 为什么 Arrays.asList(...).toArray().getClass() 在 JDK 8 和 9 中给出不同的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53696569/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com