TL之StringBuilder构建字符串

来源:互联网 发布:微信拓客软件 编辑:程序博客网 时间:2024/04/29 11:52
   我们都知道怎样用String去构建字符串,但常常也会被一些细节困扰。由于Java语言给我们带来的很多方便,很多时候程序员也便渐渐不去考虑一些效率问题了。这远远不像曾经学C或C++的时候纠结算法,效率的抓狂年代。
    最近开始下定决心仔细学习下Java基础知识部分,就把一些觉得比较容易被大家忽视,也同样是很重要的(只要你认为重要就好)知识点拿出来和大家资源共享一下。大多数是在《Core java》系列上整理和搜集下来的。
    Why we talked about StringBuilder,why should wo use it?
   Occasionally, you need to build up strings from shorter strings, such as keystrokes orwords from a file. It would be inefficient to use string concatenation for this purpose.
    Every time you concatenate strings, a new String object is constructed. This is time consuming and it wastes memory. Using the StringBuilder class avoids this problem.
    Follow these steps if you need to build a string from many small pieces. First, construc an empty string builder:
   StringBuilder builder = new StringBuilder();
   Each time you need to add another part, call the append method.
   builder.append(ch); // appends a single character
   builder.append(str); // appends a string
   When you are done building the string, call the toString method. You will get a String
   object with the character sequence contained in the builder.
   String completedString = builder.toString();

那么StringBuffer呢?
   The StringBuilder class was introduced in JDK 5.0. Itspredecessor, StringBuffer, is slightly less efficient, but it allows multiple threads to add or remove characters. If all string editing happens in a single thread (which is usually the case), you should use StringBuilder
   instead. The APIs of both classes are identical.
   要想更深地了解体会构建字符串的几种方式的区别,看看他们的API 然后敲上几行小代码测试下不就可以了哈?

0 0