Why don't the wrapper classes for Primitives have a setter?

北慕城南 提交于 2019-12-05 12:07:15

1) With a setter, the wrapper types would be mutable. Immutability is a good thing in many ways... threading, general understandability of the code etc. Personally I think it's a shame that Calendar and Date are mutable, for example.

In fact, your expansion of x++; isn't quite right - it uses Integer.valueOf which doesn't always create a new value. For example:

Integer x = 5;
x++;
Integer y = 5;
y++;

// This prints true    
System.out.println(x == y); // Compare references

Only a limited range of Integer values are cached like this (the spec defines what values must behave this way, but allows for a wider range if the JRE wishes to do so)... but it does mean that it won't always be creating a new object.

2) Yes, Java doesn't have pass by reference. Frankly I very rarely find that to be a problem. How often do you really need to swap the values of variables?

Wrapper classes are usually not used unless you need to put them into a collection. If they were mutable it would make problems if used inside sets and as keys for hashtables.

Sets and hashtables need the hash value to be always the same.

Caching Integers in the range from -128 to 127 requires immutable Integers. Consider the follwoing code:

Integer id = Integer.valueOf(1);  // a new Integer, cached in Integer class

// and somewhere else

Integer key = Integer.valueOf(1);  // returns the cached value

Now if Integer was mutable and had a setter and someone did

key.setValue(2);  // not legal Java code, just for demonstration

this would change the value of id too and, to a lot of peoples surprise:

Integer one = Integer.valueOf(1);
if (one != 1)
   System.out.println("Surprise! I know, you expected `1`, but ...");

In Java, Strings and wrapper classes are designed as immutable to avoid accidental changes to the data. You can check the below article for further information.

Why Strings and Wrapper classes are immutable in java?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!