String str1 = "zxhtom";
String str2 = new String("zxhtom");
String z1 = "zxhtom";
String z2 = "zxhtom";
通过上图我们可以了解 z1 , z2两个变量其实引用的是同一内存地址 。 所以z1==z2 为true .
到这里引发出为什么String被设计为不可变 。 上列中z1 被修改成zxh . 如果String是可变得那么z2就会被莫名其妙修改成zxh .
在上部中我们提到String的常量池。针对常量池引发思考 【String.intern()】
该方法的功能就是扩充【常量池】。z2.intern() 表示判断常量池中是否存在与该值相同的对象如果有则返回该对象的引用。 如果没有则将该值注册到内存中。注意这里并不是将z2对象注册过去。而是将z2的值注册进去。
String z1=new String("zxhtom");
String z2=z1.intern();
System.out.println( z1==z1.intern() );
System.out.println( z1.hashCode()+" "+z2.hashCode() );
System.out.println( z2==z1 );
System.out.println( z2==z1.intern() );
false
-688175064 -688175064
false
true
public static void main(String[] args) {
String x = new String("ab");
change(x);
System.out.println(x);
}
public static void change(String x) {
x = "cd";
}
本文地址:https://blog.csdn.net/u013132051/article/details/107456720
如对本文有疑问, 点击进行留言回复!!
[杭电多校2020]第一场 1004 Distinct Sub-palindromes
Swift -- 将本地生成的UIImage进行持久化保存(存到文件中fileManager.createFile)
网友评论