∞. 기술 면접/7. 자바

04. 기술면접 - 자바 - 래퍼 클래스 (Wrapper Class)

THE HEYDAZE 2021. 10. 20. 14:09
공부목적으로 다른 블로그의 글을 그대로 따라치면서 작성되었습니다. 저작권 문제 시, 비공개 처리하겠습니다

Wrapper Class

프로그램에 따라 기본 타입의 데이터를 객체로 취급해야 하는 경우가 있다 예를들어, 메소드의 인수로 객체 타입만 요구
되면, 기본 타입의 데이터형을 그대로 사용할 수 없다. 이 때 기본타입의 데이터를 먼저 객체로 변환한 후 작업을 수행해야 한다

// 사용 불가
List<int> list = new ArrayList<>();

// 사용 가능
List<Integer> list = new ArrayList<>();

// 사용 가능 (Array 는 reference type 이기 때문)
List<int[]> list = new ArrayList<>();

 

오토 박싱(Auto Boxing) 과 오토 언박싱(Auto Un Boxing)

Boxing 은 primitive type -> wrapper class 로 변환 하는 것을 말한다

UnBoxing 은 wrapper class -> primitive type 로 변환 하는 것을 말한다

JDK 1.5부터는 박싱과 언박싱이 필요한 상황에서 자바 컴파일러가 이를 자동으로 처리해 준다. 이렇게 자동화된 박싱과 언박싱을 오토 박싱(AutoBoxing)과 오토 언박싱(AutoUnBoxing)이라고 부른다.

Integer num = new Integer(17); // 박싱
int n = num.intValue();        // 언박싱
System.out.println(n); // 출력 값: 17


Character ch = 'X'; // Character ch = new Character('X'); : 오토박싱
char c = ch;        // char c = ch.charValue();           : 오토언박싱
System.out.println(c); // 출력 값: X

 

primitive type 과 wrapper class 
public class Wrapper03 {
    public static void main(String[] args) {
      Integer num1 = new Integer(10);
      Integer num2 = new Integer(20);
      Integer num3 = new Integer(10);

      System.out.println(num1 < num2);       // true
      System.out.println(num1 == num3);      // false
      System.out.println(num1.equals(num3)); // true
    }
}

부등호 연산에서는 가능하지만 == (동등비교)는 인스턴스 값을 비교하는 게 아닌 인스턴스의 주소를 비교한다
(hash code)