为什么整数在Java中是不可变的? [英] Why are Integers immutable in Java?

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

问题描述

我知道整数在Java中是不可变的。但是为什么它是这样设计的?

I know Integers are immutable in Java. But why it is designed this way?

在提出这个问题之前我经历了其他答案:

I went through other answers before asking this question:

整数是否可变

i ++仍然适用于Java中的不可变整数?

为什么Java包装类是不可变的?

但是我找不到要求Integer不可变的用例。
是否存在类似String的技术原因?

But I couldn't find the use case which mandates the Integer to be immutable. Are there any technical reasons like there are for String?


  1. 字符串用作网络连接,数据库URL等参数。如果它是可变的,它很容易被破坏。

  2. 支持StringPool工具。

  3. 支持使用字符串作为参数的类加载机制。字符串是可变的导致加载错误的类。

我知道有像 AtomicInteger for mutable。

I understand there are wrappers like AtomicInteger for mutable.

更新:

从对话中,没有普遍的理由可以强制整数是不可变的。然而,通过做不变量,它提供了答案中提到的一些奖励。

From the conversation, there is no universal reason that could mandate the Integers being immutable. However by doing immutable it provides some bonus as mentioned in the answers.

例如安德烈


缓存的可能性。

possibility to cache.

其他人正在减少全球状态

Others are reducing global state

更容易多线程


推荐答案

您将找不到 java.lang 包装必须为不可变。仅仅因为这是一个设计决策。他们本来可以另有决定。语言设计者必须在 mutable immutable 之间进行选择。他们选择了 immutable 。就是这样。

You won't find a mandatory reason why java.lang wrappers must be immutable. Simply because it's a design decision. They could have decided otherwise. The language designers had to choose between mutable and immutable. And they chose immutable. That's it.

虽然有一些引人注目的(IMO)理由让它们不可变

There are some compelling (IMO) reasons though to make them immutable:

它与 String 一致。您为 String 提供 immutable 的原因同样适用于 Integer 等。 (例如,考虑属性映射中的端口号)。 这通常适用于任何可变类型

It's consistent with String. The same reasoning you provided for String to be immutable applies to Integer etc. as well (e.g. think of a port number in a property map). This generally applies to any mutable type.

不可变的类型排除了过多的难以发现的错误,可以通过修改通过修改通过修改通过以下方式获得的值来不必要地改变对象成员值一个 getter 当类型不可变 时,它可以节省大量防御性复制。最臭名昭着的例子是 java.util.Date ,这通常很难用,因为它是 mutable (除了API问题)。

Immutable types rule out a plethora of hard to find mistakes one can make where one involuntarily changed an objects member value by modifying the value obtained through a getter. It saves a lot of defensive copying when the type is immutable. The most infamous example is java.util.Date, which is generally a pain to use because it's mutable (API issues aside).

同样,不可变类型允许使用共享实例,例如 Integer 对常用值有效(参见 Integer.valueOf(int))。

Also immutable types allow for the use of shared instances, like e.g. Integer does for commonly used values (see Integer.valueOf(int)).

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

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