Mutable π Immutable, Final
β Mutable
can be modified after initialization
encapsulate: getter, setter, private, final field
need to synchronize access for multi thread
- String Builder
- Stirng Buffer
- java.util.Date
β Immutable
cannot be modified after initialization
ν μμμ μ μ₯λ κ°μ λ³κ²½ν μ μλ κ²
preferred in multi threading, as it guarantees thread saftey
곡μ μμμ΄ Immutableνλ€λ©΄ μ¬λ¬κ°μ μ°λ λκ° μ½κ³ μ¨λ μ λ°λλκΉ safe!
- int
- long
- float
- double
- String
- legacy, wrapper classes
I changed value from 1 to 3. Does this mean Integer is mutable?
1
2
3
4
Integer i=1;
i=3;
//λ°κΏ¨λλ°μ??
// μλ, ν μμμ μλ‘μ΄ κ°μ²΄κ° μμ±λ κ²μ΄λ€.
NO. New object in heap created. and Integer with value 1 will be discared by GC
β Final
μ΄κΈ°ν μ΄νμ κ° λ³κ²½ λΆκ°
immutable
1
2
final Integer i=1;
i=3; //β compile error.
https://www.geeksforgeeks.org/mutable-and-immutable-objects-in-java-1/
This post is licensed under CC BY 4.0 by the author.