String对象的不可变性
这篇文章讲的不错: https://blog.csdn.net/thetimelyrain/article/details/105368076
public static void main(String[] args) {
//通过反射来破坏String
String str = "张三";
System.out.println(str);
try {
Field field = String.class.getDeclaredField("value");
field.setAccessible(true);
char[] value;
value = (char[])field.get(str);
value[0] = '王';
System.out.println(str);
} catch (Exception e) {
e.printStackTrace();
}
}
String热门面试题
String为什么被设计成不可变的
1. 由于经常需要字符串的增删改查,所以设计成只读的话既可以保证线程安全
2. 在保存一些密码的时候可以防止别人修改(因为String不可更改)
3. 由于很多的键被用来当做集合中的key,所以对应的String对象应该有一个固定的hashCode,不可变和HashCode是绝配
String的小练习
String s1 = "Programming";
String s2 = new String("Programming");
String s3 = "Program";
String s4 = "ming";
String s5 = "Program" + "ming";
String s6 = s3 + s4;
System.out.println(s1 == s2); //false
System.out.println(s1 == s5); //true
System.out.println(s1 == s6); //false 使用符号引用进行加载没有编译器的优化
System.out.println(s1 == s6.intern()); //true
System.out.println(s2 == s2.intern()); //false