Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Change value of a Float object

Tags:

java

I have looked inside the javadoc for Float, but there does not seem to be any way to modify the value after construction?

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...

Is there a way to change the value of the object? Alternatively, is there another wrapper class available that would allow this?

like image 638
hmn Avatar asked Jun 16 '26 09:06

hmn


2 Answers

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.

like image 93
arshajii Avatar answered Jun 17 '26 21:06

arshajii


Float is a value object (immutable object).

It makes no sense to alter direclty its value without reinstantiating a new one with the new value.

Indeed, Float has no concept of Identity, it's just a pure VALUE, thus doesn't need a mutable behaviour.

That could be interest you, to understand the concept:

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

like image 31
Mik378 Avatar answered Jun 17 '26 22:06

Mik378



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!