Practical example for Immutable class

末鹿安然 提交于 2019-12-06 07:46:52

问题


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 ?


回答1:


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.

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.




回答2:


A good example is related to hashing. A class overrides the equals() and hashCode() methods so that it can be used in data structures like HashSet and (as keys in) HashMap, and the hash code is typically derived by some identifying member attributes. However, if these attributes were to change then so would the object's hash code, so the object is no longer usable in a hashing data structure.




回答3:


Java provides a nice example: String.




回答4:


This article has a good color example (since color definitions don't change). http://www.ibm.com/developerworks/java/library/j-jtp02183/index.html



来源:https://stackoverflow.com/questions/9203419/practical-example-for-immutable-class

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