java-StringBuffer和StringBuilder…

发布时间:2016-12-8 15:51:00 编辑:www.fx114.net 分享查询网我要评论
本篇文章主要介绍了"java-StringBuffer和StringBuilder…",主要涉及到java-StringBuffer和StringBuilder…方面的内容,对于java-StringBuffer和StringBuilder…感兴趣的同学可以参考一下。

class StringBufferDemo {  public static void main(String[] args)  {   String s = "abc" + 58 + "def"+true+'g';   System.out.println(s);   //注意:byte和short不能向StringBuffer中添加,需要提升为int型   StringBuffer sb = new StringBuffer().append("abc").append(58)    .append("def").append(true).append('g');   //StringBuffer s1 = new StringBuffer("abcde");   StringBuilder s1 = new StringBuilder("abcde");   System.out.println(s1.delete(1,3));          //ade   System.out.println(s1.insert(2,"kq"));   //adkqe   System.out.println(s1.replace(2,4,"uiop"));  //aduiope   System.out.println(s1.reverse());            //epoiuda   System.out.println(s1.toString());    //epoiuda    //JDK 1.5 新类型:StringBuilder,用于多线程不安全,但是用于单线程时效率高,   //所以一把用不安全的StringBuilder,多线程时还是用StringBuffer安全.   int [] ary = {1,2,3,4,5};   System.out.println(intAryToString1(ary));   System.out.println(intAryToString2(ary));   //操作练习   String s2 = "java";   String s3 = "hello";   test1(s2, s3);   System.out.println(s2 + "..." + s3);   StringBuffer sb1 = new StringBuffer("java");   StringBuffer sb2 = new StringBuffer("hello");   test2(sb1, sb2);   System.out.println(sb1 + "..." + sb2);    //字符串部分反转输出.   String s4 = "abcdef";   System.out.println(partReverse(s4, 1, 4));  }     //该方法不断用字符串连接的方式产生对象,动态分配内存,耗费资源.  public static String intAryToString1(int [] ary)  {   String str = "";    for (int x = 0; x < ary.length; x++)   {    if (x != ary.length - 1)     str += ary[x]+",";    else     str += ary[x];   }   return str;  }  //操作一个对象,资源消耗少,故采用这方式效率更高.  public static String intAryToString2(int [] ary)  {   StringBuilder sb = new StringBuilder();    for (int x = 0; x < ary.length; x++)   {    if (x != ary.length - 1)     sb.append(ary[x]+",");    else     sb.append(ary[x]);   }   return sb.toString();  //转为字符串  }  public static void test1(String s1, String s2)  {   s1.replace("a", "n");   s2 = s1;  }  public static void test2(StringBuffer s1, StringBuffer s2)  {   s1.append(s2);   s2 = s1;  }  //字符串部分反转  public static String partReverse(String s, int start, int end)  { //  String s1 = s.substring(0, start); //  String s2 = s.substring(end, s.length()); //  StringBuilder sb1 = new StringBuilder(new StringBuilder(s.substring(start, end)).reverse()); //  return new StringBuffer().append(s1).append(sb1).append(s2).toString(); //  优化后的代码:   String sub = s.substring(start, end);   sub = new StringBuilder(sub).reverse().toString();   return new StringBuilder(s).replace(start, end, sub).toString();  } }

上一篇:Pro Android 4 第六章 构建用户界面以及使用控件(一)
下一篇:(C++实现)——解释器模式(Interpreter Pattern)

相关文章

相关评论