package day13;
/*
* 为什么我们要讲解类之间的转换?
* A--B转换
* 我们把A转换为B,其实是为了使用B的功能。
* 我们可能要的结果是A类型,所以还得转回来。
*
* String和String Buffer的相互转换?
*
* StringBuffer面试题?
* 1:String、StringBuffer、StringBuilder的区别?
* A:String内容不可能变,而后两者均可变的。
* B:StringBuffer是同步的,数据安全,效率低。StringBuilder是不同步,数据不安全,效率高。
* 2:StringBuffer和数组的区别?
* 二者都可以看做一个容器,装其他的数据。
* 但是呢?StringBuffer的数据最终是一个字符串数据。
* 而数组可以放置的多种数据,但必须是同一种类型数据。
* 3:形式参数问题
* String作为参数传递
* StringBuffer作为参数传递
* 形式参数:
* 基本类型:形式参数的改变不影响实际参数
* 引用类型:形式参数的改变直接影响实际参数
* 注意:
* String作为参数传递,效果和基本类型作为参数传递是一样的。*****
*
* */
public class StringBufferTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
//String --StringBuffer;
String s ="hello";
//注意:StringBuffer是不能把字符串的值赋值给StringBuffer
// StringBuffer sb="hello";//错误
//方式1
StringBuffer sb = new StringBuffer(s);
//方式2
StringBuffer sb2 = new StringBuffer();
sb2.append(s);
System.out.println("sb:"+sb);
System.out.println("sb2:"+sb2);
System.out.println("----------------");
//StringBuffer--String
StringBuffer sb3 = new StringBuffer("java");
//方式1
String str=new String(sb3);
//方式2
String str2=sb3.toString();
System.out.println("str:"+str);
System.out.println("str2:"+str2);
System.out.println("----------------");
//面试题
String s1="hello";
String s2="world";
System.out.println(s1+"---"+s2);//hello--world
change(s1,s2);
System.out.println(s1+"---"+s2);//hello--world
StringBuffer sb6=new StringBuffer("hello");
StringBuffer sb7 = new StringBuffer("world");
System.out.println(sb6+"---"+sb7);//hello--world
change(sb6,sb7);
System.out.println(sb6+"---"+sb7);//hello--worldworld
}
public static void change(StringBuffer sb6, StringBuffer sb7) {
// TODO Auto-generated method stub
sb6=sb7;
sb7=sb7.append(sb6);
}
public static void change(String s1, String s2) {
// TODO Auto-generated method stub
s1=s2;
s2=s1+s2;
}
}
总结:
String:适用于少量的字符串操作的情况
StringBuilder:适用于单线程下在字符缓冲区进行大量操作的情况
StringBuffer:适用多线程下在字符缓冲区进行大量操作的情况