Friday, July 22, 2016

String is Immutable and property hash is not final




How is that possible? We have read all over the internet that all properties must be final to make a class immutable.

Well it is possible but with some rules/restrictions and that is access to mutable properties/fields must provide same result every time we access it.

In String class hashcode actually calculated on the final array of characters which is not going to change if String has constructed. Therefore immutable class can contain mutable fields/properties but it has to make sure that access to field/property will produce the same result every time it is accessed.

No comments:

Post a Comment