What is meant by immutable?

后端 未结 17 1614
天命终不由人
天命终不由人 2020-11-22 02:27

This could be the dumbest question ever asked but I think it is quite confusing for a Java newbie.

  1. Can somebody clarify what is meant by immutable? <
17条回答
  •  借酒劲吻你
    2020-11-22 03:15

    "immutable" means you cannot change value. If you have an instance of String class, any method you call which seems to modify the value, will actually create another String.

    String foo = "Hello";
    foo.substring(3);
    <-- foo here still has the same value "Hello"
    

    To preserve changes you should do something like this foo = foo.sustring(3);

    Immutable vs mutable can be funny when you work with collections. Think about what will happen if you use mutable object as a key for map and then change the value (tip: think about equals and hashCode).

提交回复
热议问题