Immutable & Mutable

효딩딩·2022년 8월 23일
0

자바의 객체의 타입에는 Immutable 타입과 mutable타입이 있다.

  • 객체들은 기본적으로 heap영역에 할당되고 stack영역에 래퍼런스 값을 갖는 참조 변수들로 접근 가능하다.
  • mutable 오브젝트는 생성된 후 변경 가능하고, immutable 오브젝트는 생성된 후 변경이 불가능 하다. 즉 상태를 변경할 수 있고 없고의 차이가 있습니다.

immutable(불변) 객체

  • 이름에서 알 수 있듯이 변경 불가능,바뀌지 않는 객체이다.
  • immutable 객체의 종류에는 대표적으로 String, Boolean, Integer, Float, Long 등이 있다. (객체이므로 String을 제외하면 primitive의 래퍼타입이다).

mutable(가변) 객체

  • mutable객체는 불변객체와 다르게 heap영역에 생성된 객체를 변경 할 수 있다.
  • 대표적인 가변 객체는 List, ArrayList, HashMap,StringBuilder,StringBuffer 등이 있다.
  • 가변객체를 multi-thread 환경에서 사용하려면 별도의 동기화 처리를 해줘야한다.

출처: https://cantcoding.tistory.com/41

(영문)

A mutable object can be changed after it's created, and an immutable object can't.

  • In Java, everything (except for strings) is mutable by default:

  • In Java, state of the immutable object can’t be modified after it is created but definitely reference other objects.

They are very useful in multithreading environment because multiple threads can’t change the state of the object so immutable objects are thread safe. Immutable objects are very helpful to avoid temporal coupling and always have failure atomicity.

On the other hand, Mutable objects have fields that can be changed, immutable objects have no fields that can be changed after the object is created.

Source: https://www.tutorialspoint.com/difference-between-mutable-and-immutable-object

profile
어제보다 나은 나의 코딩지식

0개의 댓글