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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值