Can I have StringBuilder in an immutable class

感情迁移 提交于 2019-12-07 23:58:19

问题


If I create an immutable class. All the fields have to be final. If I use stringbuilder in that like this final StringBuilder s = new StringBuilder("Hello ");

, then the append function can append the value of the s and the class wont be immutable. Please advice.


回答1:


It's "shallow-immutable" in that you can't change the fields themselves, but it's not fully immutable - which means you lose pretty much all the benefits associated with immutability.

Basically to achieve immutability, all the constituent parts must either be naturally immutable, or sometimes you can get away with using something which is mutable but a) you constructed it, so nothing else has a reference to it; b) you never expose a reference to it; c) you never mutate it yourself.

For example, you can write an immutable type that uses java.util.Date (although I'd strongly recommend using java.time) - you'd just need to make sure that if you ever wanted to return a date from a method, you cloned it instead of returning the value of the field.



来源:https://stackoverflow.com/questions/57981224/can-i-have-stringbuilder-in-an-immutable-class

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