Does autoboxing call valueOf()?

前端 未结 4 2116
北恋
北恋 2020-12-01 11:45

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

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


        
4条回答
  •  情深已故
    2020-12-01 12:36

    Autoboxing is absolutely implemented using valueOf() ...in the OpenJDK. If that's your implementation, read on... if not, skip to below.

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

    Java documentation states that Boolean.valueOf() always returns Boolean.TRUE or Boolean.FALSE, therefore your reference comparisons in these cases will succeed.

    ((Integer)1) == Integer.valueOf(1)
    

    For this particular example, under the OpenJDK implementation with default settings, it will probably work by virtue of the fact that you picked a value < 128 which is cached at startup (although this can be overridden as a commandline arg). It may also work for larger values if it's frequently used enough to be cached. Unless you're working under "safe" assumptions about the Integer cache, don't expect the reference comparison to be an equality.

    Long, Short, Character and Byte incidentally implement this caching too, but unlike Integer, it's not tunable. Byte will always work if you're comparing autobox/valueOf() references since obviously, you can't go out of range. Float and Double will unsurprisingly always create a new instance.


    Now, in purely generic terms? See this section of the JLS - you MUST be given equal references for boolean and any int or char within the -128 to 127 range. There are no guarantees for anything else.

提交回复
热议问题