当前位置: 移动技术网 > IT编程>开发语言>Java > 深入Java不可变类型的详解

深入Java不可变类型的详解

2019年07月22日  | 移动技术网IT编程  | 我要评论

学警出更粤语版,南条真琴,kaki 博客

我们先看下面一个例子:
复制代码 代码如下:

    import java.math.biginteger; 
    public class bigproblem { 
        public static void main(string[ ] args) { 
            biginteger fivethousand  = new biginteger("5000"); 
            biginteger fiftythousand = new biginteger("50000"); 
            biginteger fivehundredthousand = new biginteger("500000"); 
            biginteger total = biginteger.zero; 
            total.add(fivethousand); 
            total.add(fiftythousand); 
            total.add(fivehundredthousand); 
            system.out.println(total); 
        } 
    } 

你可能会认为这个程序会打印出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:
复制代码 代码如下:

    import java.math.biginteger; 
    public class bigproblem { 
        public static void main(string[] args) { 
            biginteger fivethousand  = new biginteger("5000"); 
            biginteger fiftythousand = new biginteger("50000"); 
            biginteger fivehundredthousand = new biginteger("500000"); 
            biginteger total = biginteger.zero; 
            total = total.add(fivethousand); 
            total = total.add(fiftythousand); 
            total = total.add(fivehundredthousand); 
            system.out.println(total); 
        } 
    } 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网