java基础

基本类型包装类注意点:

  Byte, Short, Long,Integer类会将 -128~127范围内的值,创建初始化对象存入jvm内存中缓存。Character 缓存的范围是 0~127。

  以上类的valueof()方法生成的包装类,会先从jvm缓存中获取,缓存中没有才创建。

  valueof方法源码:

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);
    }

  包装类型“==”比较,例:

@Test
    public void test09(){
        Long a = Long.valueOf(2),a1 = Long.valueOf(2);
        System.out.println(a == a1);   // 结果 true
        Long b = 2L,b1 = 2L;
        System.out.println(b == b1);    // true
        Long c = new Long(2),c1 = new Long(2);
        System.out.println(c == c1);   //false
        Long d = 129L,d1 = 129L;
        System.out.println(d == d1);   // false
    }

由上面例子可知,Long b =2L;这种方式的赋值,值在 -128~127范围内,从缓存中获取对象; Long d =129L,不在缓存中,使用new Long()创建新对象。这种模式可叫做"享元模式":将类的某些对象初始化,重复使用。

 基本类型的内存大小和取值范围

byte:  占1字节,取值 -2^7 ~ 2^7-1;

short:  占2个字节,取值 -2^15 ~ 2^15-1;

int:占4个字节,取值 -2^31  ~  2^31-1;

long:占8个字节,取值 -2^63  ~  2^63-1;

float:占4个字节,取值 ... ; double:占8个字节,取值...;

char:占2个字节,取值0 ~ 65535;boolean:占1个字节,取值 true,false;

 

posted @ 2022-12-10 12:12  bobokeyea  阅读(23)  评论(0)    收藏  举报