Java中的不可变类型

我们先看下面一个例子:

[java]  view plain copy
  1. import java.math.BigInteger;  
  2. public class BigProblem {  
  3.     public static void main(String[ ] args) {  
  4.         BigInteger fiveThousand  = new BigInteger("5000");  
  5.         BigInteger fiftyThousand = new BigInteger("50000");  
  6.         BigInteger fiveHundredThousand = new BigInteger("500000");  
  7.         BigInteger total = BigInteger.ZERO;  
  8.         total.add(fiveThousand);  
  9.         total.add(fiftyThousand);  
  10.         total.add(fiveHundredThousand);  
  11.         System.out.println(total);  
  12.     }  
  13. }  

你可能会认为这个程序会打印出555000。毕竟,它将total设置为用BigInteger表示的0,然后将5,000、50,000和500,000加到了这个变量上。如果你运行该程序,你就会发现它打印的不是555000,而是0。很明显,所有这些加法对total没有产生任何影响。

对此有一个很好理由可以解释:BigInteger实例是不可变的。String、BigDecimal以及包装器类型:Integer、Long、Short、Byte、Character、Boolean、Float和Double也是如此,你不能修改它们的值。我们不能修改现有实例的值,对这些类型的操作将返回新的实例。起先,不可变类型看起来可能很不自然,但是它们具有很多胜过与其向对应的可变类型的优势。不可变类型更容易设计、实现和使用;它们出错的可能性更小,并且更加安全[EJ Item 13]。

为了在一个包含对不可变对象引用的变量上执行计算,我们需要将计算的结果赋值给该变量。这样做就会产生下面的程序,它将打印出我们所期望的555000:

[java]  view plain copy
  1. import java.math.BigInteger;  
  2. public class BigProblem {  
  3.     public static void main(String[] args) {  
  4.         BigInteger fiveThousand  = new BigInteger("5000");  
  5.         BigInteger fiftyThousand = new BigInteger("50000");  
  6.         BigInteger fiveHundredThousand = new BigInteger("500000");  
  7.         BigInteger total = BigInteger.ZERO;  
  8.         total = total.add(fiveThousand);  
  9.         total = total.add(fiftyThousand);  
  10.         total = total.add(fiveHundredThousand);  
  11.         System.out.println(total);  
  12.     }  
  13. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值