java字符串链接的注意

代码如下:

<span style="font-size:18px;">import java.util.ArrayList;
import java.util.List;


public class Test {
	public static void main(String[] args) {
		List<String> fileList = new ArrayList<String>();
		for (int i = 0; i < 5; i++) {
			int theMax = 0;
			fileList.add("file" + theMax + i);
		}
		for (String file : fileList) {
			System.out.println(file);
		}
	}
}</span>
输出:

file00
file01
file02
file03
file04

结果竟然不是:

file0
file1
file2
file3
file4

原因如下:

问题:将一些字符串连接起来
  解决之道:
  三种方法:
  1、直接用+号连接,编译器将构造一个StringBuffer对象,并调用其append方法
  2、自己构造StringBuffer对象,有append()方法将返回对StringBuffer对象本身的引用。
  3、通过toString方法
  代码:
  /**
   * StringBufferDemo: 用三种方式构造同样的字符串
   */
  public class StringBufferDemo {
      public static void main(String[] argv) {
          String s1 = "Hello" + ", " + "World";
          System.out.println(s1);
  
          // 构造StringBuffer对象,并添加一些字符串
          StringBuffer sb2 = new StringBuffer();
          sb2.append("Hello");
          sb2.append(',');
          sb2.append(' ');
          sb2.append("World");
  
          // 将StringBuffer值转换为字符串,并输出
          String s2 = sb2.toString();
          System.out.println(s2);
  
          // 现在重复上面的工作,但是采用更为简明的方式
          // 典型的“real-world”JAVA
  
          StringBuffer sb3 = new StringBuffer().append("Hello").
              append(',').append(' ').append("World");
          System.out.println(sb3.toString());
  
      }
  } 
  
  小结:事实上,不论修改了StringBuffer中的多少字符,所有的方法append(),delete(),deleteCharAt(),insert(),replace(),reverse()等等都只返回改StringBuffer对象的引用,这样十分有利编程。  


fileList.add("file" + theMax + i);
这里的写法实际上是调用 StringBuffer的append,那么当我们append(theMax)之后,然后再append(i);

如果想得到file0 file1 file2 file3 file4这样的结果。就需要这样子:

fileList.add("file" + (theMax + i));

你可能感兴趣的:(java字符串链接的注意)