引用不可变和对象不可变的例子

对象不可变

String s1="Hi";
String s2=s1;
System.out.println("操作前:");
System.out.println("s1的内容:"+s1+"  s2的内容:"+s2);
System.out.println("s1的hashcode:"+s1.hashCode()+",s2的hashcode:"+s2.hashCode());
s1+=" Loststar";
System.out.println("操作后:");
System.out.println("s1的内容:"+s1+"  s2的内容:"+s2);
System.out.println("s1的hashcode:"+s1.hashCode()+",s2的hashcode:"+s2.hashCode());

结果:

操作前:
s1的内容:Hi  s2的内容:Hi
s1的hashcode:2337,s2的hashcode:2337
操作后:
s1的内容:Hi Loststar  s2的内容:Hi
s1的hashcode:746752949,s2的hashcode:2337

引用不可变

用了final修饰变量

测试1:

final StringBuilder sb = new StringBuilder("Hi");
System.out.println("操作前:");
System.out.println("sb的内容:"+sb+", sb的hashcode:"+sb.hashCode());
sb.append(" Loststar");
System.out.println("操作后:");
System.out.println("sb的内容:"+sb+", sb的hashcode:"+sb.hashCode());

结果:

操作前:
sb的内容:Hi, sb的hashcode:2003749087
操作后:
sb的内容:Hi Loststar, sb的hashcode:2003749087

测试2:

final StringBuilder sb = new StringBuilder("Hi");
sb=new StringBuilder("Hi Loststar");

结果报错:java: 无法为最终变量sb分配值


引用不可变和对象不可变的例子
https://blog.loststar.tech/posts/8bda9476/
作者
loststar
发布于
2021年12月14日
许可协议