Programming Languages/Java

[Java] - 오토박싱, 언박싱 (Autoboxing and Unboxing)

Jesse 2021. 12. 29. 21:47

Autoboxing

자바로 개발을 하다보면 int와 같은 primitive type이 클래스가 아니기 때문에 불편을 겪은적이 있다.

예를 들어, 정수로 되어 있는 리스트를 만들어 본다고 하자

public class Main {

    public static void main(String[] args) {

        ArrayList<int> intArrayList = new ArrayList<int>();
        
    }

이렇게 정수로 된 ArrayList를 만드려고 하면 에러가 나온다.

ArrayList에 들어갈수 있는건 클래스여야 하기 때문이다..

물론, 이런 상황에 대한 해법으로 int를 클래스로 직접 만들수도 있다.

import java.util.ArrayList;

class IntClass {
    private int myValue;

    public IntClass(int myValue) {
        this.myValue = myValue;
    }

    public int getMyValue() {
        return myValue;
    }

    public void setMyValue(int myValue) {
        this.myValue = myValue;
    }
}


public class Main {

    public static void main(String[] args) {
        ArrayList<IntClass> intClassArrayList = new ArrayList<IntClass>();
        intClassArrayList.add(new IntClass(54));
    }
}

ArrayList에 int를 저장하기 위해 IntClass라는 클래스를 새로 만들었다.

이렇게 primitive type을 클래스를 바꿔주는 역할을 하는 클래스를 Wrapper Class라고 한다.

자바에서는 사용자가 굳이 이렇게 Wrapper class를 따로 코드로 정의하지 않아도 되도록

자바 컴파일러가 제공하는 이걸 오토박싱이라고 한다.

Wrapper Class가 하는 일이 primitive type을 클래스로 포장하는 일이기 때문에

Autoboxing이라고 부르는것 같다.

import java.util.ArrayList;

public class Main {

    public static void main(String[] args) {
    
        Integer myIntValue = 56;

    }
}

56은 primitive type이지만 Integer 클래스의 값으로 할당해도 전혀 컴파일할때 문제가 되지 않는다.

 

Unboxing

오토박싱이 포장을 하는거라면 언박싱은 반대로 포장을 푸는 것이다.

import java.util.ArrayList;

public class Main {

    public static void main(String[] args) {

        Integer myIntValue = 56; // 오토박싱
        int myInt = myIntValue.intValue(); // 언박싱

    }
}

int에는 Integer라는 wrapper class가 이미 built-in 되어 있기 때문에 쉽게 오토박싱과 언박싱을 할수 있다.