StringBuffer 需要注意的地方--final

StringBuffer 需要注意的地方如下,如果StringBuffer 变量被final修饰后:

package test;

public class TestBuffer {
	public static void main(String[] args) {

		final StringBuffer sb = new StringBuffer().append("abc");
		sb.append("EF");
		System.out.println(sb);
		
	}
	
}


输出结果:

abcEF

在JavaSE的官方文档上:

http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.12.4

说明如下:

Once a final variable has been assigned, it always contains the same value. If a final variable holds a reference to an object, then the state of the object may be changed by operations on the object, but the variable will always refer to the same object.

So it is OK to manipulate state of object pointed by a

sb.append("Welcome"); //is OK

but you can't make a to point to another object

final StringBuffer a = new StringBuffer("Hello");
a = new StringBuffer("World"); //this wont compile
参考1:http://stackoverflow.com/questions/15557113/need-clarification-on-final-stringbuffer-object

参考2:http://www.javaranch.com/journal/2003/04/immutable.htm


Which classes are Immutable?

To finish up, lets discuss the common Java classes that are immutable and those that aren't. Firstly, all of the  java.lang  package wrapper classes are immutable:

Boolean, Byte, Character, Double, Float, Integer, Long, Short, String.

As in the Person classes we discussed, java.util.Date objects are not immutable. The classes java.math.BigInteger and BigDecimal are not immutable either, although maybe they should have been


你可能感兴趣的:(JAVA编程)