问题描述
我看不到布尔包装器类变为不可变的原因.
I can't see the reason why the Boolean wrapper classes were made Immutable.
为什么不像在Commons lang中实现MutableBoolean那样实现Boolean Wrapper,实际上可以对其进行重置.
Why the Boolean Wrapper was not implemented like MutableBoolean in Commons lang which actually can be reset.
有人对此有任何想法/理解吗?谢谢.
Does anyone have any idea/understanding about this ? Thanks.
推荐答案
因为2
是2.明天不会是3
.
Because 2
is 2. It won't be 3
tomorrow.
默认为
Immutable,在多线程情况下尤其如此,尤其,它使代码更易于阅读和维护.例子:Java Date
API,它充满了设计缺陷.如果Date
是不可变的,则该API将非常简化.我知道Date
操作会创建新日期,而不必寻找修改它们的API.
Immutable is always preferred as the default, especially in multithreaded situations, and it makes for easier to read and more maintainable code. Case in point: the Java Date
API, which is riddled with design flaws. If Date
were immutable the API would be very streamlined. I would know Date
operations would create new dates and would never have to look for APIs that modify them.
阅读并发实践以了解不可变类型的真正重要性.
Read Concurrency in Practice to understand the true importance of immutable types.
但还要注意,如果出于某种原因想要可变类型,请使用AtomicInteger
AtomicBoolean
等.为什么选择Atomic
?因为通过引入可变性,您引入了对线程安全性的需求.如果您的类型保持不变,则不需要这些,因此在使用可变类型时,您还必须付出考虑线程安全和使用concurrent
包中的类型的代价.欢迎来到并发编程的美好世界.
But also note that if for some reason you want mutable types, use AtomicInteger
AtomicBoolean
, etc. Why Atomic
? Because by introducing mutability you introduced a need for threadsafety. Which you wouldn't have needed if your types stayed immutable, so in using mutable types you also must pay the price of thinking about threadsafety and using types from the concurrent
package. Welcome to the wonderful world of concurrent programming.
此外,对于Boolean
-我要求您命名一个可能要执行的操作,该操作关心布尔值是否可变.设置为true?使用myBool = true
.那是重新分配,而不是突变.否定? myBool = !myBool
.相同的规则.请注意,不变性是一种功能,而不是一种约束,因此,如果您可以提供它,则应该-在这种情况下,当然可以.
Also, for Boolean
- I challenge you to name a single operation that you might want to perform that cares whether Boolean is mutable. set to true? Use myBool = true
. That is a re-assignment, not a mutation. Negate? myBool = !myBool
. Same rule. Note that immutability is a feature, not a constraint, so if you can offer it, you should - and in these cases, of course you can.
请注意,这也适用于其他类型.整数最微妙的是count++
,但这只是count = count + 1
,除非您关心原子获取值...在这种情况下,请使用可变的AtomicInteger
.
Note this applies to other types as well. The most subtle thing with integers is count++
, but that is just count = count + 1
, unless you care about getting the value atomically... in which case use the mutable AtomicInteger
.
这篇关于为什么像Java中的Boolean这样的Wrapper类是不可变的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!