概要:区别、string、面试题
一、三者区别
拼接、可变、线程安全
1、共同类:StringBuilder与StringBuffer都继承自AbstractStringBuilder类:1)用字符数组保存字符串,char[] value,可变。2)expandCapacity、append、insert、indexOf等公共方法
2、同步锁:StringBuffer对方法(或调用方法)加了同步锁 synchronized,线程安全,StringBuilder没有
3、效率:StirngBuilder 相比使用StringBuffer 仅能获得10%~15% 左右的性能提升,却要冒线程安全风险
StringBuilder > StringBuffer > String;但String str = "hello"+ "world" > StringBuilder st = new StringBuilder().append("hello").append("world")
总结:
操作少量数据 = String
多线程操作大量数据 = StringBuffer
单线程操作操作大量数据 = StringBuilder
二、String类
通过char数组来保存字符串
任何改变都会生成新对象、不影响原对象
三、常见面试题
1、String a = "hello2"; String b = "hello" + 2; System.out.println((a == b)); 输出结果
true。"hello"+2 编译期被优化成"hello2",运行期,变量a、b指向同一对象
2、String a = "hello2"; String b = "hello"; String c = b + 2; System.out.println((a == c));
false,有符号引用存在,String c = b + 2不在编译期被优化,不把b+2当做字面常量来处理,生成对象在堆上
3、(同上)String a = "hello2"; final String b = "hello"; String c = b + 2; System.out.println((a == c));
true。final修饰变量,在class文件常量池中保存一个副本,不通过连接访问,对final变量访问,在编译期间都会直接被替代为真实值
https://www.cnblogs.com/dolphin0520/p/3778589.html