不可变类的实际示例 [英] Practical example for Immutable class

查看:63
本文介绍了不可变类的实际示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很明显,不变性增加了可重用性,因为它在每个状态变化中都会创建新的对象.有人可以告诉我一个需要不可变类的实际情况吗?

It is obvious that immutability increases the re-usability since it creates new object in each state change.Can somebody tells me a practical scenario where we need a immutable class ?

推荐答案

考虑java.lang.String.如果它不是一成不变的,那么每次您想拥有一个不会被改变的字符串时,您都必须创建一个副本.

Consider java.lang.String. If it weren't immutable, every time you ever have a string you want to be confident wouldn't change underneath you, you'd have to create a copy.

另一个例子是集合:能够接受或返回一个真正不变的集合(例如来自Guava的信息-不仅仅是可变集合的不变视图),并且对它不会被改变充满信心.

Another example is collections: it's nice to be able to accept or return a genuinely immutable collection (e.g. from Guava - not just an immutable view on a mutable collection) and have confidence that it won't be changed.

无论这些是否算作需求",我都不知道-但我不想在没有它们的情况下发展.

Whether those count as "needs" or not, I don't know - but I wouldn't want to develop without them.

这篇关于不可变类的实际示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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