3

我查看了 Float 的 javadoc 内部,但似乎没有任何方法可以在构造后修改值?

Float f = new Float(1.23f);
[...]
f.setValue(3.14f); // Nothing like this seems to exist...
f = 3.14f; // "f" now points to a new object, not what I want...

有没有办法改变对象的值?或者,是否有另一个可用的包装类允许这样做?

4

3 回答 3

5

You cannot change the value of a Float; all of the primitive wrapper classes are immutable. You could create your own (mutable) wrapper class if you want to add this functionality, or take a look at MutableFloat from the Apache Commons.

于 2013-06-23T12:40:41.260 回答
4

Float是一个值对象(不可变对象)。

直接改变它的值而不用新值重新实例化一个新值是没有意义的。

确实,Float没有 VALUE 的概念Identity,它只是一个纯VALUE,因此不需要可变行为。

您可能会对理解这个概念感兴趣:

http://devlicio.us/blogs/casey/archive/2009/02/13/ddd-entities-and-value-objects.aspx

于 2013-06-23T12:42:41.867 回答
3

All of the java.lang package wrapper classes are immutable: Boolean, Byte, Character, Double, Float, Integer, Long, Short, String.

Hence there are no setters or any other methods to change the value of the Float object.

于 2013-06-23T12:41:24.740 回答