问题描述
Java中的所有原始包装类都是不可变对象吗?字符串是不可变的。什么是其他不可变对象?
Are all primitive wrapper classes in Java immutable objects? String is immutable. What are the other immutable objects?
推荐答案
任何不能为您提供更改数据的方法都是不可变的- 就这么简单。是的,所有原始包装类型都是不可变的,就像 String
一样。 ,和是其他示例。
Any type which doesn't give you any means to change the data within it is immutable - it's as simple as that. Yes, all the primitive wrapper types are immutable, as is String
. UUID, URL and URI
are other examples.
虽然内置Java API中的 Calendar
和 Date
是可变的, 中的许多类型都是不可变的 - 在我看来,这是一个为什么Joda Time更容易使用。如果一个对象是不可变的,你可以在代码中的其他地方保留对它的引用,而不必担心其他一些代码是否会进行更改 - reason 更容易你的代码。
Although Calendar
and Date
in the built-in Java API are mutable, many of the types within Joda Time are immutable - and to my mind, this is one reason why Joda Time is easier to work with. If an object is immutable, you can keep a reference to it somewhere else in your code and not have to worry about whether or not some other piece of code is going to make changes - it's easier to reason about your code.
我的意思是 java.lang .Integer
等如其他地方所述, Atomic *
类是可变的,实际上有是为了达到他们的目的。在标准的原始包装类集和包装原始值的类集之间我的想法有所不同。
by which I mean java.lang.Integer
etc. As noted elsewhere, the Atomic*
classes are mutable, and indeed have to be in order to serve their purpose. There's a difference in my mind between "the standard set of primitive wrapper classes" and "the set of classes which wrap primitive values".
你可以编写自己的可变包装器很容易上课:
You can write your own mutable wrapper class very easily:
public class MutableInteger
{
private int value;
public MutableInteger(int value)
{
this.value = value;
}
public int getValue()
{
return value;
}
public void setValue(int value)
{
this.value = value;
}
}
所以你可以看到,没有什么本质上不可变的包装类 - 只是标准的设计是不可变的,因为没有提供任何改变包装值的方法。
So as you can see, there's nothing inherently immutable about wrapper classes - it's just that the standard ones were designed to be immutable, by virtue of not providing any way to change the wrapped value.
请注意,这允许在装箱时重复使用相同的对象,对于常见值:
Note that this allows for the same object to be used repeatedly when boxing, for common values:
Integer x = 100;
Integer y = 100;
// x and y are actually guaranteed to refer to the same object
Integer a = 1000;
Integer b = 1000;
// a and b *could* refer to the same object, but probably won't
这篇关于所有原始包装类都是不可变对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!