本文介绍了autoboxing是否调用valueOf()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试确定以下陈述是否保证为真:

I'm trying to determine whether the following statements are guaranteed to be true:

((Boolean)true) == Boolean.TRUE
((Boolean)true) == Boolean.valueOf(true)
((Integer)1) == Integer.valueOf(1)

我一直认为自动装箱相当于在相应类型上调用 valueOf() 。我见过的每一个 似乎我的假设。但我在JLS中找到的只有以下内容():

I've always assumed that autoboxing was equivalent to calling valueOf() on the corresponding type. Every discussion that I've seen on the topic seems to support my assumption. But all I could find in the JLS was the following (§5.1.7):

这描述了行为。但似乎没有任何保证实际调用 valueOf(),这意味着理论上可以有一个实现为自动装箱的值保留一个单独的专用缓存。在这种情况下,缓存的自动装箱值和常规缓存的装箱值之间可能没有相同的身份。

That describes behavior similar* to that of valueOf(). But there doesn't seem to be any guarantee that valueOf() is actually invoked, meaning there could theoretically be an implementation that keeps a separate, dedicated cache for autoboxed values. In such a case, there might not be identity equality between cached autoboxed values and regular cached boxed values.

事实上说明了 li.add(i)编译为 li.add(Integer.valueOf(i)),其中 i INT 。但我不知道该教程是否应被视为权威来源。

Oracle's autoboxing tutorial states matter-of-factly that li.add(i) is compiled to li.add(Integer.valueOf(i)), where i is an int. But I don't know whether the tutorial should be considered an authoritative source.

推荐答案

我首先考虑你的问题是

I first tought your question was a dupe of What code does the compiler generate for autoboxing?

然而,在您对@ElliottFrisch发表评论后,我发现它有所不同:

However, after your comment on @ElliottFrisch I realized it was different :

对于其他读者,假设表现得那样 表示使用 valueOf

For other readers, assume that "behaves that way" means using valueOf.

请记住,Java有多个编译器。为了合法,他们必须遵守。因此,只要这里的所有规则都得到尊重,就无法保证内部如何实现自动装箱。

Remember that there are multiples compilers for Java. To be "legal" they must follow the contract given in the JLS. Therefore, as long as all the rules here are respected, there is no guarantee of how autoboxing is internally implemented.

但我认为没有理由不使用 valueOf ,特别是它使用缓存的值,并且是这篇文章由Joseph D. Darcy撰写。

But I don't see any reason to not use valueOf, specially that it uses the cached values and is the recommended way as per this article by Joseph D. Darcy.

这篇关于autoboxing是否调用valueOf()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!