본문 바로가기
Java 배우기

Autoboxing and Unboxing 오토박싱과 언박싱

by 노화방지 Anti-aging Hairstyle 2016. 1. 5.
반응형

오토 박싱(Autoboxing)은 자바 컴파일러가 원시 타입과 해당 객체 래퍼 클래스 사이에서 만드는 자동 변환입니다. 

예를 들어, int를 Integer, double Double 등으로의 변환입니다.
변환이 다른 길로 가면, 그것을 
unboxing이라 합니다.
가장 간단한 autoboxing의 예:

Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an int to an Integer, a double to a Double, and so on. If the conversion goes the other way, this is called unboxing.

Here is the simplest example of autoboxing:

Character ch = 'a';

이 섹션의 예제의 나머지는 generics를 사용합니다.
미처 generics의 신택스에 익숙하지 않다면,  Generics (Updated) lesson을 참조하십시오.

The rest of the examples in this section use generics. If you are not yet familiar with the syntax of generics, see the Generics (Updated) lesson.


다음 코드를 검토해보십시오:

Consider the following code:

List<Integer> li = new ArrayList<>();
for (int i = 1; i < 50; i += 2)
    li.add(i);


int 값을 Integer 객체가 아닌 원시타입(primitive types)으로  li에 추가할지라도, 코드는 컴파일 합니다.
liInteger 객체들의 목록이고, int 값의 목록이 아니기 때문에, 자바 compiler가 compile-time error를 발행하지 않는지 의아해 할 것입니다.
이것이 i로부터 객체
Integer를 생성해서 객체를 li에 추가시키기 때문에, 파일러가 오류를 발생시키지 않습니다.
이와 같이, compiler는 런타임에 previous code를 following으로 변환합니다:

Although you add the int values as primitive types, rather than Integer objects, to li, the code compiles. Because li is a list of Integer objects, not a list of int values, you may wonder why the Java compiler does not issue a compile-time error. The compiler does not generate an error because it creates an Integer object from i and adds the object to li. Thus, the compiler converts the previous code to the following at runtime:

List<Integer> li = new ArrayList<>();
for (int i = 1; i < 50; i += 2)
    li.add(Integer.valueOf(i));

Converting a primitive value (an int, for example) into an object of the corresponding wrapper class (Integer) is called autoboxing. The Java compiler applies autoboxing when a primitive value is:

  • Passed as a parameter to a method that expects an object of the corresponding wrapper class.
  • Assigned to a variable of the corresponding wrapper class.

Consider the following method:

public static int sumEven(List<Integer> li) {
    int sum = 0;
    for (Integer i: li)
        if (i % 2 == 0)
            sum += i;
        return sum;
}

Because the remainder (%) and unary plus (+=) operators do not apply to Integer objects, you may wonder why the Java compiler compiles the method without issuing any errors. The compiler does not generate an error because it invokes theintValue method to convert an Integer to an int at runtime:

public static int sumEven(List<Integer> li) {
    int sum = 0;
    for (Integer i : li)
        if (i.intValue() % 2 == 0)
            sum += i.intValue();
        return sum;
}

Converting an object of a wrapper type (Integer) to its corresponding primitive (int) value is called unboxing. The Java compiler applies unboxing when an object of a wrapper class is:

  • Passed as a parameter to a method that expects a value of the corresponding primitive type.
  • Assigned to a variable of the corresponding primitive type.

The Unboxing example shows how this works:

import java.util.ArrayList;
import java.util.List;

public class Unboxing {

    public static void main(String[] args) {
        Integer i = new Integer(-8);

        // 1. Unboxing through method invocation
        int absVal = absoluteValue(i);
        System.out.println("absolute value of " + i + " = " + absVal);

        List<Double> ld = new ArrayList<>();
        ld.add(3.1416);    // Π is autoboxed through method invocation.

        // 2. Unboxing through assignment
        double pi = ld.get(0);
        System.out.println("pi = " + pi);
    }

    public static int absoluteValue(int i) {
        return (i < 0) ? -i : i;
    }
}

The program prints the following:

absolute value of -8 = 8
pi = 3.1416

Autoboxing and unboxing lets developers write cleaner code, making it easier to read. The following table lists the primitive types and their corresponding wrapper classes, which are used by the Java compiler for autoboxing and unboxing:


Primitive typeWrapper class
booleanBoolean
byteByte
charCharacter
floatFloat
intInteger
longLong
shortShort
doubleDouble


반응형

댓글