记录学习享元模式时遇到的

String s1 = "hello";
String s2 = "hello";
String s3 = "he" + "llo";
String s4 = "hel" + new String ("lo");
String s5 = new String ("hello");
String s6 = s5.intern(); //拿到s5对应的常量地址
String s7 = "h";
String s8 = "ello";
String s9 = s7 + s8;
String s10 = "h"+"ello";

System.out.println(s1 == s2); //true
System.out.println(s1 == s3); //true
System.out.println(s1 == s4); //false
System.out.println(s1 == s5); //false
System.out.println(s4 == s5); //false
System.out.println(s1 == s6); //true
System.out.println(s1 == s9); //false 编译阶段,s7 s8都是变量,jvm不会做优化,会在堆里分配内存
System.out.println(s1 == s10); //true 编译阶段就处理成hello

//jvm利用享元模式对String的优化,编译阶段对所能看到的放到常量池中,运行阶段直接使用


Integer a =Integer.valueOf(100);
Integer b = 100;

Integer c =Integer.valueOf(1000);
Integer d = 1000;

System.out.println(a == b); //true
System.out.println(c == d); //false

//Integer的valueof方法里在-128到127中有享元模式实现的缓存池,其外的都是调用new
//Long的valueof也是-128到127
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值