为什么Java包装类是不可变的? [英] Why are Java wrapper classes immutable?

查看:686
本文介绍了为什么Java包装类是不可变的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道适用于一般不可变类的通常原因,即

I know the usual reasons that apply to general immutable classes, viz


  1. 不能作为副作用更改

  2. 很容易理解他们的状态

  3. 固有的线程安全

  4. 无需提供克隆/复制构造函数/工厂复制方法

  5. 实例缓存

  6. 无需防御性副本。

  1. can not change as a side effect
  2. easy to reason about their state
  3. inherently thread safe
  4. no need to provide clone/copy constructor/factory copy method
  5. instance caching
  6. no need for defensive copies.

但是,包装类表示基本类型,基本类型是可变的。那么为什么包装类不可变?

However, wrapper classes represent primitive types, and primitive types are mutable. So why aren't wrapper classes mutable?

推荐答案


但是,包装类代表基本类型,原始类型(String除外)是可变的。

However, wrapper classes represent primitive types, and primitive types (except String) are mutable.

首先,String不是基本类型。

Firstly, String isn't a primitive type.

其次,谈论可变的原始类型是没有意义的。如果您更改变量的值,则:

Secondly, it makes no sense to talk about the primitive types being mutable. If you change the value of a variable like this:

int x = 5;
x = 6;

这不会改变数字5 - 它正在改变 x的值

That's not changing the number 5 - it's changing the value of x.

虽然包装类型可能已经变得可变,但在我看来这样做会很烦人。我经常使用这些类型的只读集合,并且不希望它们可以更改。偶尔我想要一个可变的等价物,但在这种情况下,很容易想出一个,或者使用 Atomic * 类。

While the wrapper types could have been made mutable, it would have been annoying to do so, in my view. I frequently use readonly collections of these types, and wouldn't want them to be changeable. Very occasionally I want a mutable equivalent, but in that case it's easy enough to come up with one, or use the Atomic* classes.

我发现自己希望 Date Calendar 比我发现自己想要的更频繁整数是可变的...(当然我通常会选择Joda Time,但Joda Time 的一个好处是不变性。)

I find myself wishing that Date and Calendar were immutable far more often than I find myself wanting Integer to be mutable... (Of course I normally reach for Joda Time instead, but one of the benefits of Joda Time is immutability.)

这篇关于为什么Java包装类是不可变的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆