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
记录学习享元模式时遇到的
最新推荐文章于 2024-08-04 17:16:44 发布