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

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

    One factor is that, if Strings were mutable, objects storing Strings would have to be careful to store copies, lest their internal data change without notice. Given that Strings are a fairly primitive type like numbers, it is nice when one can treat them as if they were passed by value, even if they are passed by reference (which also helps to save on memory).

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 14:29

    Strings in Java are not truly immutable, you can change their value's using reflection and or class loading. You should not be depending on that property for security. For examples see: Magic Trick In Java

    0 讨论(0)
  • 2020-11-22 14:30

    One should really ask, "why should X be mutable?" It's better to default to immutability, because of the benefits already mentioned by Princess Fluff. It should be an exception that something is mutable.

    Unfortunately most of the current programming languages default to mutability, but hopefully in the future the default is more on immutablity (see A Wish List for the Next Mainstream Programming Language).

    0 讨论(0)
  • 2020-11-22 14:30

    There is an exception for nearly almost every rule:

    using System;
    using System.Runtime.InteropServices;
    
    namespace Guess
    {
        class Program
        {
            static void Main(string[] args)
            {
                const string str = "ABC";
    
                Console.WriteLine(str);
                Console.WriteLine(str.GetHashCode());
    
                var handle = GCHandle.Alloc(str, GCHandleType.Pinned);
    
                try
                {
                    Marshal.WriteInt16(handle.AddrOfPinnedObject(), 4, 'Z');
    
                    Console.WriteLine(str);
                    Console.WriteLine(str.GetHashCode());
                }
                finally
                {
                    handle.Free();
                }
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-22 14:32

    It's largely for security reasons. It's much harder to secure a system if you can't trust that your Strings are tamperproof.

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