Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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)

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):

If the value p being boxed is an integer literal of type int between -128 and 127 inclusive (§3.10.1), or the boolean literal true or false (§3.10.3), or a character literal between 'u0000' and 'u007f' inclusive (§3.10.4), then let a and b be the results of any two boxing conversions of p. It is always the case that a == b.

That describes behavior identical 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.

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.


*It's a slightly weaker guarantee than valueOf(), as it only refers to literal values.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
419 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

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

I know the compiler behaves that way. I'm trying to figure out whether that behavior is guaranteed.

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

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...