Basic data types Java source Interpreting the wrappers (a) corresponding to the eight basic types of package type

EDITORIAL words

    When a recent project, encountered a small bug, so long as a programmer, so now they get to know basic things, ashamed - In this mark, hope not to repeat

problem:

Long long1=127L;
Long long2 = 127L;

System.out.println(long1==long2);//true
System.out.println(long1.equals(long2));//true


Long long1=128L;
Long long2 = 128L;

System.out.println(long1==long2);//false
System.out.println(long1.equals(long2));//true
    

  Package type is also used == comparison, why <= 127 could,> 128 can not?

problem analysis:

1. Comparison of the two values ​​using the method of packaging valueOf class when the value of the cache and the method of -128 to 127, exceeding this value, it creates a new package objects, two objects are compared with == then returned definitely false. The following is the type of Long valueOf source

public static Long valueOf(long l) {
        final int offset = 128;
        if (l >= -128 && l <= 127) { // will cache
            return LongCache.cache[(int)l + offset];
        }
        return new Long(l);
}

  

2. What are the different types of methods valueOf cache value it? The following five are cached value

Types of Cache scope Value range
Character       0~127 0~65535
Byte  -128~127 -128~127
Short  -128~127 -32768 ~ 32767
Integer  -128~127 -2147483648 ~ 2147483647
Long  -128~127 -9223372036854775808 ~ 9223372036854775807

 

 

 

 

 

 

 

 

 

3.Float and Double type is cached value it? The following is the source of Float valueOf

public static Float valueOf(float f) {
        return new Float(f);
}

  As can be seen no cache value, it can not be directly compared using ==

 

4. Some basic types and other features on the package type, refer to the following address blog

Understanding Java source code (a) corresponding to the eight basic types of package type

 

to sum up:

1. If the two values ​​are substantially the wrappers of the type recommended directly equals method.

 

Guess you like

Origin www.cnblogs.com/xiaozhijing/p/10968715.html