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

后端 未结 17 2144
不思量自难忘°
不思量自难忘° 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: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();
                }
            }
        }
    }
    

提交回复
热议问题