我可以在不可变的类中使用StringBuilder吗 [英] Can I have StringBuilder in an immutable class

查看:68
本文介绍了我可以在不可变的类中使用StringBuilder吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我创建一个不可变的类.所有字段都必须是最终字段.如果我像这样使用stringbuilder final StringBuilder s = new StringBuilder("Hello");

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 ");

,则append函数可以附加s的值,并且该类将是不可变的.请指教.

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

推荐答案

它是浅不可变的",因为您不能更改字段本身,但是它不是完全不可变的-这意味着您几乎失去了与不变性相关的所有好处.

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.

基本上要实现不变性,所有组成部分必须自然不变的,或者有时,您可以摆脱使用可变的东西,但是a)构造它,因此没有其他参考资料; b)您绝不会公开对其的引用; c)您永远不会自己突变.

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.

例如,您可以编写使用java.util.Date的不可变类型(尽管我强烈建议使用java.time)-您只需要确保是否曾经想从方法中返回日期即可,则将其克隆,而不是返回该字段的值.

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.

这篇关于我可以在不可变的类中使用StringBuilder吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆