Skip to content

Instantly share code, notes, and snippets.

@taekwon-dev
Last active February 15, 2023 02:53
Show Gist options
  • Save taekwon-dev/96da371c2fed22293c46830c81f91d38 to your computer and use it in GitHub Desktop.
Save taekwon-dev/96da371c2fed22293c46830c81f91d38 to your computer and use it in GitHub Desktop.

[Java] Wrapper Class, Boxing, Unboxing

기본형 타입 (int, boolean 등)을 참조형 타입으로 나타낸 것이 Wrapper Class 이다. 기본형 변수를 객체로 표현할 때 사용한다. 이 때 기본형 타입을 Wrapper Class 로 변환하는 과정을 Boxing 이라 하고 그 반대 과정을 Unboxing 이라 한다.

image [ 그림 1 ]

// Boxing (int to Integer) 
Integer i = Integer.valueOf(1);  

// Unboxing (Integer to int) 
int i = Integer.intValue(new Integer(1)); 

[ 코드 1 ]

Auto Boxing, Unboxing 은 이름에서 알 수 있듯이 자동으로 [ 코드 1 ] 과 같은 작업이 처리되는 것을 의미한다. Auto Boxing, Unboxing 을 통해 개발자는 보다 깔끔하고 가독성이 좋은 코드를 작성할 수 있게 됐다. 예시를 통해서 한 번 확인해보자.

List<Integer> list = new ArrayList<>();
for (int i = 0; i < 50; i += 2) {
		list.add(i); // Auto Boxing 
		list.add(Integer.valueOf(i)); // Boxing		 
}

[ 코드 2 ]

[ 코드 2 ] 의 List 에서는 기본형 타입을 지원하지 않기 때문에 반드시 참조형 타입의 데이터를 넣어야 한다. 하지만 [ 코드 2 ] 의 for loop 를 보면, int 가 리스트에 추가되는 것을 볼 수 있는데, 이는 별도의 변환 과정 (Boxing) 이 자동으로 처리되었기 때문에 가능한 것이다.


| Reference

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment