Are Java wrapper classes really immutable?

倾然丶 夕夏残阳落幕 提交于 2019-11-29 05:32:22

i is a reference. Your code change the reference i to point to a different, equally immutable, Integer.

final Integer i = Integer.valueOf(5);

might be more useful.

Immutable means that the object state cannot be changed. In your case you haven't changed the object new Integer(5), but you have changed the reference i to point to another object. Hope it is clear:)

The compiler autoboxes primitive values, this means that

Integer value = 6;

will be compiled as

Integer value = Integer.valueOf(6);

Integer.valueOf will return an Integer instance with the given value. In your case i will now reference the Integer(6) instead of the Integer(5), the Integer(5) object itself will not change.

To see this you can do following

Integer i = new Integer(5);//assign new integer to i
Integer b = i;//b refences same integer as i
i = 6;//modify i
System.out.println(i +"!="+b);

This will print 6!=5, if the integer instance had been modified it would print 6!=6 instead.

To clarify this is only meant to show how an assignment to Integer only modifies the reference and does not alter the Integer instance itself. As user @KNU points out it does not prove or show the immutability of Integer, as far as I can tell the immutability is only indirectly given by the lack of modifying methods in its API and the requirement that instances returned by Integer.valueOf have to be cached for a certain range.

The reason i = 6 works is that auto-boxing is intercepting and turning it into i = new Integer(6). Thus as @Peter said, you are now pointing at a new object.

All wrapper classes in java are immutable. We can't change the value of a wrapper class object once created, i.e., can't change the value wrapped inside the object. Because wrapper classes are used as object form of primitive data types and if they are mutable, data inconsistencies will occur in runtime. However, you can change the wrapper class reference variable to hold another object.

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