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

后端 未结 17 2145
不思量自难忘°
不思量自难忘° 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:23

    I know this is a bump, but... Are they really immutable? Consider the following.

    public static unsafe void MutableReplaceIndex(string s, char c, int i)
    {
        fixed (char* ptr = s)
        {
            *((char*)(ptr + i)) = c;
        }
    }
    

    ...

    string s = "abc";
    MutableReplaceIndex(s, '1', 0);
    MutableReplaceIndex(s, '2', 1);
    MutableReplaceIndex(s, '3', 2);
    Console.WriteLine(s); // Prints 1 2 3
    

    You could even make it an extension method.

    public static class Extensions
    {
        public static unsafe void MutableReplaceIndex(this string s, char c, int i)
        {
            fixed (char* ptr = s)
            {
                *((char*)(ptr + i)) = c;
            }
        }
    }
    

    Which makes the following work

    s.MutableReplaceIndex('1', 0);
    s.MutableReplaceIndex('2', 1);
    s.MutableReplaceIndex('3', 2);
    

    Conclusion: They're in an immutable state which is known by the compiler. Of couse the above only applies to .NET strings as Java doesn't have pointers. However a string can be entirely mutable using pointers in C#. It's not how pointers are intended to be used, has practical usage or is safely used; it's however possible, thus bending the whole "mutable" rule. You can normally not modify an index directly of a string and this is the only way. There is a way that this could be prevented by disallowing pointer instances of strings or making a copy when a string is pointed to, but neither is done, which makes strings in C# not entirely immutable.

提交回复
热议问题