Wrapper Class?
자바의 자료형은 primitive type과 reference type으로 나뉜다.
- primitive type : char, int, float, double, boolean 등
- reference type : class, interface 등
기본 자료타입(primitive type) 데이터를 객체(Object)로 표현해야 할 때 객체로 다루기 위해 사용하는 클래스를 wrapper class라고 한다.
Wrapper Class 구조도
Wrapper Class를 사용하는 이유
- 기본 데이터 타입(primitive type)을 Object로 변환할 수 있다.
- parse + 기본 타입명을 이용해 문자열을 기본 타입 값으로 변환할 때 사용된다.
- java.util 패키지의 클래스는 객체만 처리하므로 Wrapper class가 도움이 된다.
- ArrayList 등과 같은 Collection 프레임 워크의 데이터 구조는 primitive type이 아닌 객체 타입만 저장하게 되고 Wrapper Class를 사용해 AutoBoxing과 AutoUnBoxing이 일어난다.
- 멀티스레딩에서 동기화를 지원하려면 객체가 필요하다.
Boxing과 UnBoxing
Boxing : Primitive 타입의 값을 Wrapper 객체로 만드는 과정
UnBoxing : Wrapper 객체에서 Primitive 타입의 값을 얻어내는 과정
public static void main(String[] args) {
// Boxing
Integer num = new Integer(17);
// UnBoxing
int n = num.intValue();
}
AutoBoxing과 AutoUnBoxing
AutoBoxing : Wrapper class type에 primitive type의 값이 대입될 경우
public static void main(String[] args) {
// AutoBoxing
Integer num = 17;
// AutoUnBoxing
int n = num;
}
출처
'JAVA > Java 문법' 카테고리의 다른 글
[Java] ArrayList와 List의 차이 (0) | 2022.02.05 |
---|