在字符串比较中 , 你是否明白这几个输出语句的结果?
public class Test {
public static void main(String[] args) {
String s1 = "hello";
String s2 = "hello";
String s3 = new String("hello");
String s4 = new String("hello");
System.out.println(s1 == s2);//true
System.out.println(s1 == s3);//false
System.out.println(s3 == s4);//false
}
}
在
Java
程序中,类似于:
1
,
2
,
3
,
3.14
,
“hello”
等字面类型的常量经常频繁使用,
为了使程序的运行速度更快、
更节省内存
,
Java
为
8
种基本数据类型和
String
类都提供了
常量池
:
常量池主要是用来提升效率的 .
常量池是什么?
比如 : 家里给大家打生活费的方式1 . 家里经济拮据 , 每月定时打生活费 , 有时可能会晚, 最差情况下可能需要向家里张口要, 速度慢2 . 家里有矿 , 一次性打一年的生活费放到银行卡中, 自己随用随取, 速度非常快方式2 就是池化技术的一种示例, 钱放在卡上, 随用随取, 效率非常高, 常见的池化技术比如 : 数据库连接池, 线程池等.
通过下面的图来了解一下常量池吧
intern方法
对于下面这个代码 , 大家想一下在s2这个引用赋值之前 常量池里面有没有"abc"呢?
public static void main(String[] args) {
char[] ch = new char[]{'a','b','c'};
String s1 = new String(ch);
String s2 = "abc";
System.out.println(s1 == s2);
}
答案是没有的
将上面的代码加上一句 :
public static void main(String[] args) {
char[] ch = new char[]{'a','b','c'};
String s1 = new String(ch);
s1.intern();
String s2 = "abc";
System.out.println(s1 == s2);
}
可以看出结果就成为true了!
以上就是我对常量池的一些理解 , 希望可以帮到大家~~~