0

Byte, Short and Integer maintains a buffer pool values representing -128 to 127. Character pools values representing '\u0000' to '\u007F'.

So that I can understand that why all above wrapper classes are Immutable.

But, Float and Double do not maintain any buffer pool then what is the purpose of making these classes as Immutable?

I read it from below link:
https://coderanch.com/t/670745/java/Wrapper-Classes-Immutable

Shrirang Kadale
  • 472
  • 1
  • 4
  • 16
  • 1
    There's probably a more actual reason, but for me the question one should ask is **why would you make it mutable?**. Just imagine the confusions that would result if you could call `floatVar.setValue(2f)`, and then count on auto-boxing on the following line to use `floatVar` as a primitive parameter (or the reverse, where a `updateMyFloat(Float floatParam)` method calls `floatParam.setValue(3)` and the caller invokes ``updateMyFloat(1.1f)`)... – ernest_k Jan 25 '19 at 05:41
  • @Thilo I don't think this question is duplicate as I am asking about only floating point wrapper classes. – Shrirang Kadale Jan 28 '19 at 05:20

2 Answers2

0

First of all, if Byte, Short, Character and Integer are immutable, it would be very inconsistent to make Double and Float mutable.

Mutability also has it's cost - you cannot share the same resource safely between multiple threads. Copying them on demand is very cheap.

I also do not see a use case to make them mutable - if you want to use it as some combined in/out parameter, it's a poor design.

Dorian Gray
  • 2,913
  • 1
  • 9
  • 25
0

If the standard primitive wrappers were mutable, then you would effectively break the boxing / unboxing feature.

 Integer mutable = 1;
 mutable.setValue(2);
 Integer one = 1;
 System.out.println(one);   // Prints '1'?  Or '2'?

If you want mutable primitive wrappers, they more or less exist already in the form the Java SE "atomic" classes; i.e. AtomicBoolean, AtomicInteger and AtomicLong. These have the advantage (but also the cost) of being thread-safe.

Other alternatives include one element arrays, using a 3rd-party alternative such as the Apache Commons MutableInt (etcetera) classes ... or writing your own classes at about 10 lines of code a time.

See also:

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216