Java中的String pool
public String intern()
返回字符串对象的规范化表示形式。
一个初始时为空的字符串池,它由类 String 私有地维护。当调用 intern 方法时,如果池已经包含一个等于此 String 对象的字符串(该对象由 equals(Object) 方法确定),则返回池中的字符串。否则,将此 String 对象添加到池中,并且返回此 String 对象的引用。
它遵循对于任何两个字符串 s 和 t,当且仅当 s.equals(t) 为 true 时,s.intern() == t.intern() 才为 true。
所有字面值字符串和字符串赋值常量表达式都是内部的。
返回:
一个字符串,内容与此字符串相同,但它保证来自字符串池中。
# 使用常量赋值时, 指向的是pool中的引用
String s0 = "HelloWorld"; // id:24
# 指向的是相同的引用 String s00 = "HelloWorld"; // id:24 System.out.println(s00 == s0);//true
# 使用变量赋值时, 是新的对象 String s1 = "Hello".concat("World"); // id:27
System.out.println(s1 == s0);
# 使用变量赋值时, 是新的对象, 但是内部的参数, 实际也是指向pool中的对象
String s10 = new String("HelloWorld"); // id:24 System.out.println(s10 == s0);
# 使用intern会直接指回pool中的对象 String s2 = s1.intern(); // id:24 System.out.println(s2 == s0);
# 再次调用并不会修改这种关系 String s3 = s2.intern(); // id:24 System.out.println(s3 == s2);//true System.out.println(s3 == s0);//true System.out.println(); String a = new String("ab"); String b = new String("ab"); String c = "ab"; String d = "a" + "b"; String e = "b";
# 使用变量赋值时, 会产生新的对象引用 String f = "a" + e; System.out.println(b.intern() == a); System.out.println(b.intern() == c); // true System.out.println(b.intern() == d); // true System.out.println(b.intern() == f); System.out.println(b.intern() == a.intern()); // true
.
分类:
Java
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程