Mutable strings in Java

前端 未结 1 1155
盖世英雄少女心
盖世英雄少女心 2021-02-20 00:30

As almost everybody knows strings in Java are immutable. Recently I discovered something that might suggest that it\'s not always true. Let\'s try out this code:



        
相关标签:
1条回答
  • 2021-02-20 01:21

    String literals are interned into a pool. This means that when you write

    String s1 = "Foo";
    String s2 = "Foo";
    String s3 = new String("Foo");
    

    s1 and s2 refer to the same String object, and s3 refers to another one, backed by another char array.

    In your code, you violate String's invariants by modifying the private char array holding the characters of the "Original" String literal instance. But since beforeTest refers to another String instance, it's not modified.

    Immutability is achieved by keeping fields private into an object, and not providing any method to modify this private state. By using reflection, you break all the rules of encapsulation, and you can thus violate immutability.

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