Java学习笔记|Java学习笔记(2)(字符串(2)StringBuilder)

String的内容是不可变的,在用String类型拼接字符串时会产生新对象,从而导致内存的占用增多。解决这个问题的方法就是利用StringBuilder类,它的内容是可变的。
通过API文档可知其不需导包,与String类型一样可直接使用。
  1. StringBuilder的构造
public class Stringg {public static void main(String[] args) {//第一种构造方法:无参构造 StringBuilder sb = new StringBuilder(); System.out.println("sb:"+sb+"-->sb.lenth:"+sb.length()); //第二种构造方法:利用String类型初始化 StringBuilder mv = new StringBuilder("ywq"); System.out.println("mv:"+mv+"-->mv.lenth:"+mv.length()); String lmx = "ywqwan"; StringBuilder ywq = new StringBuilder(lmx); System.out.println("ywq:"+ywq+"-->ywq.lenth:"+ywq.length()); } }

2.特点:
public class Stringg {public static void main(String[] args) {StringBuilder a = new StringBuilder(); StringBuilder b = a; System.out.println(a == b); } }

true//这说明a与b的地址是相同的

3.StringBuilder类的添加
StringBuilder类的添加可用StringBuilder.append(任意类型);
public class Stringg {public static void main(String[] args) {StringBuilder lmx = new StringBuilder(); lmx.append("ywq"); lmx.append(520); lmx.append(13.14); //lmx.append("ywq").append(520).append(13.14); System.out.println(lmx); } }

输出:ywq52013.14

4.StringBuilder类的反转
使用reverse方法
String类没有reverse方法喔
public class Stringg {public static void main(String[] args) {//StringBuilder类的添加可用StringBuilder.append(任意类型); StringBuilder lmx = new StringBuilder(); lmx.append("ywq").append(520).append(13.14); System.out.println(lmx.reverse()); } } 输出:41.31025qwy

5.StringBuilder的遍历
跟String一样,使用charAt()方法

【Java学习笔记|Java学习笔记(2)(字符串(2)StringBuilder)】6.StringBuild和String互相转换
//StringBuilder转String: StringBuilder ywq = new StringBuilder("lmx"); ywq.toString();

//String 转StringBuilder:直接构造方法就行了 String ywq = new String("lmx"); StringBuilder love = new StringBuilder(ywq);

    推荐阅读