Why can't strings be mutable in Java and .NET?

后端 未结 17 2174
不思量自难忘°
不思量自难忘° 2020-11-22 14:04

Why is it that they decided to make String immutable in Java and .NET (and some other languages)? Why didn\'t they make it mutable?

17条回答
  •  一向
    一向 (楼主)
    2020-11-22 14:40

    String is not a primitive type, yet you normally want to use it with value semantics, i.e. like a value.

    A value is something you can trust won't change behind your back. If you write: String str = someExpr(); You don't want it to change unless YOU do something with str.

    String as an Object has naturally pointer semantics, to get value semantics as well it needs to be immutable.

提交回复
热议问题