Mutable or immutable class?

后端 未结 8 1875
死守一世寂寞
死守一世寂寞 2020-12-17 21:44

I had read in some design book that immutable class improves scalability and its good practice to write immutable class wherever possible. But I think so immutable class inc

相关标签:
8条回答
  • 2020-12-17 22:08

    Just one more consideration about the subject. Using immutable object allow you to cache them and not re-create them everytime (ie Strings) it helps a lot on your application performance.

    0 讨论(0)
  • 2020-12-17 22:09

    One thing to consider: If you intend to use instances of a class as keys in a HashMap, or if you're going to put them in a HashSet, it's safer to make them immutable.

    HashMap and HashSet count on the fact that the hash code for an object remains constant as long as the object is in the map or set. If you use an object as a key in a HashMap, or if you put it in a HashSet, and then change the state of the object so that hashCode() would return a different value, then you're confusing the HashMap or HashSet and you'll get strange things; for example, when you iterate the map or set the object is there, but when you try to get it, it's as if it is not there.

    This is due to how HashMap and HashSet work internally - they organize objects by hash code.

    This article by Java concurrency guru Brian Goetz gives a good overview of the pros and cons of immutable objects.

    0 讨论(0)
提交回复
热议问题