gpt4 book ai didi

java - 什么是标量类型,为什么禁止未经检查的转换为数组类型比禁止转换为标量类型的风险更大?

转载 作者:搜寻专家 更新时间:2023-11-01 01:22:19 24 4
gpt4 key购买 nike

<分区>

来自 Effective Java Item 26 Favor Generic types

All other things being equal, it is riskier to suppress an unchecked cast to an array type than to a scalar type, which would suggest the second solution. But in a more realistic generic class than Stack, you would probably be reading from the array at many points in the code, so choosing the second solution would require many casts to E rather than a single cast to E[],which is why the first solution is used more commonly [Naftalin07, 6.7].

作者在这里所说的标量类型是什么意思,他想在这里表达什么?什么选项 1 被认为比选项 2 更危险?

代码:

// The elements array will contain only E instances from push(E).
// This is sufficient to ensure type safety, but the runtime
// type of the array won't be E[]; it will always be Object[]!
@SuppressWarnings("unchecked")
public Stack() {
elements = (E[]) new Object[DEFAULT_INITIAL_CAPACITY];
}

对比

// Appropriate suppression of unchecked warning
public E pop() {
if (size == 0)
throw new EmptyStackException();
// push requires elements to be of type E, so cast is correct
@SuppressWarnings("unchecked") E result =
(E) elements[--size];
elements[size] = null; // Eliminate obsolete reference
return result;
}

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