래퍼 클래스는 기본형을 객체로 감싸서 관리하기 편하게 만들어준다.
쉽게 이야기 하면 래퍼 클래스는 기본형을 객체로 만든 것이다.
package lang.wrpper;
public class WrapperClassMain {
public static void main(String[] args) {
Integer newInteger = new Integer(10); // 미래의 삭제 예정, 대신에 valueOf()를 사용
Integer integerObject = Integer.valueOf(10); // -128~127 자주 사용하는 숫자, 불변
Long longObj = Long.valueOf(100);
Double doubleObj = Double.valueOf(10.5);
System.out.println("integerObject = " + integerObject);
System.out.println("newInteger = " + newInteger);
System.out.println("longObj = " + longObj);
System.out.println("doubleObj = " + doubleObj);
System.out.println("내부 값 읽기");
int intValue = integerObject.intValue();
System.out.println("intValue = " + intValue);
long longValue = longObj.longValue();
System.out.println("longValue = " + longValue);
System.out.println("비교");
System.out.println("equals : " + (newInteger.equals(integerObject) ));
}
}
기본형을 래퍼 클래스로 변경하는 것을 마치 박스에 넣는 것 같다고 하여 박싱이라 한다.
new Integer()는 Java 9부터 deprecated 되었고 사용을 권장하지 않는다.
대신, Integer.valueOf()를 사용하면 된다.
Integer.valueOf()는 최적화가 되어 있다. 개발자들이 자주 사용하는 -128~127의 값을 미리 생성하고 문자열 풀처럼 이용할 수 있다.
같은 값이면 새로운 객체가 아니라 기존 객체 재사용한다.
박싱의 반대
개발자들은 오랜 기간 개발을 하다보니 기본형을 래퍼 클래스로 전환하거나, 래퍼 클래스를 변경하는 일이 잦았는데 이러한 행동이 번거로워 오토박싱을 만들었다.
package lang.wrpper;
public class AutoBoxingMain1 {
public static void main(String[] args) {
// primitive => Wrapper
int value = 7;
Integer boxedValue = Integer.valueOf(7);
System.out.println(boxedValue);
// Wrapper => primitive
int unboxedValue = boxedValue.intValue();
System.out.println(unboxedValue);
}
}
오토 박싱과 오토 언박싱은 컴파일러가 개발자 대신 valueOf, xxxValue() 등의 코드를 추가해준다.
덕분에 기본형과 래퍼형을 편안하게 바꿀 수 있다.
다만 오토박싱은 편하지만, 반복문에서는 불필요한 객체 생성이 발생할 수 있다.