기본형(primitive) vs. 래퍼 클래스(wrapper class)

Doyeon·2023년 2월 2일
0
post-thumbnail

Primitive vs. Wrapper

기본형(primitive type)과 참조형(reference type)

  • 자료형은 크게 ‘기본형’과 ‘참조형’으로 나뉜다.
  • 기본형(primitive type) : 계산을 위한 실제 값을 저장한다.
    • 논리형(boolean), 문자형(char), 정수형(byte, short, int, long), 실수형(float, double)
  • 참조형(reference type) : 객체의 주소를 저장한다.
    • 8개의 기본형을 제외한 나머지 타입들

래퍼 클래스(Wrapper Class)란?

  • 기본형 데이터 타입(primitive type)을 객체로 변환한 클래스
  • wrapper 클래스를 시용하면 기본형(primitive) 값을 객체로 다룰 수 있다.
  • 객체 생성 시, 기본형 데이터 타입을 저장하는 필드가 존재한다.
    public final class Integer extends Number implements Comparable {
    			...
    		private int value;
    			...
    }

래퍼 클래스(Wrapper Class) 사용 이유

  • 기본형 데이터 타입(primitive data type)을 객체(Object)로 변환할 수 있다.
    • primitive 타입을 객체로 만들어 null을 넣거나 메서드를 사용할 수 있다.
      Integer i = null; // 가능
      // int i = null;  // Error! 기본형에는 null을 넣을 수 없다.
      
      String s = i.toString();  // toString() 메서드 사용 가능
  • java.util 패키지의 클래스는 객체만 처리하므로 래퍼 클래스가 필요하다.
    • Date, Calendar 클래스
    • Collection Framework 관련 인터페이스와 클래스
  • Collection Framework의 데이터 구조는 기본 타입(primitive type)이 아닌 객체만 저장한다.
    • Generics 타입에 primitive는 사용할 수 없다.
      // List<int> list = new ArrayList<>();  // Error! int형과 같은 기본형은 Generics 타입에 사용불가
      List<Integer> list = new ArrayList<>();
      
      // Set<char> set = new HashSet<>();  // Error! char형 Generics타입에 사용불가
      Set<Character> set = new HashSet<>();
      
      // Map<String, int> map = new HashMap<>(); // Error! int형 사용불가
      Map<String, Integer> map = new HashMap<>();
  • 멀티쓰레딩에서 동기화를 지원하려면 객체가 필요하다.

박싱(Boxing)과 언박싱(UnBoxing)

  • 박싱(Boxing) : 기본형 데이터 타입(primitive type) → 래퍼 클래스(wrapper class)의 인스턴스로 변환
  • 언박싱(Un-Boxing) : 래퍼 클래스(wrapper class) → 기본형 타입(primitive type)으로 변환
  • 오토박싱(Auto Boxing) : 자바 컴파일러가 primitive → wrapper class 로 자동 변환
  • 오토언박싱(Auto Un-Boxing) : 자바 컴파일러가 wrapper class → primitve 로 자동 변환
    • 오토 박싱, 오토 언박싱 → Java5부터

      List<Integer> list = new ArrayList<>();
      list.add(new Integer(100)); // 객체 생성해서 넣는다.
      list.add(100); // 오토박싱 (int -> Integer)
      
      int a = 10;
      Integer b = a; // 오토 박싱 (int -> Integer)
      int c = b;  // 오토 언박싱 (Integer -> int)

래퍼 클래스(Wrapper Class)의 메서드

  • 래퍼 클래스들은 모두 equals()가 오버라이딩되어 있다. → 주소값이 아닌 객체로 값을 비교
    • 래퍼 클래스와 기본형 타입을 서로 비교할 때는 ==, equals() 모두 사용 가능하다. → 오토 박싱, 언박싱
  • 비교 연산자 사용 불가 → compareTo() 사용
  • toString() 도 오버라이딩되어 있다. → 객체가 갖고 있는 값 문자열 반환 가능
    Integer i = new Integer(100);
    Integer i2 = new Integer(100);
    
    System.out.println((i==i2));  // false -> 두 객체의 주소값이 다르므로 false
    System.out.println(i.equals(i2));  // true -> 두 객체가 가진 값이 같으므로 true
    System.out.println(i.compareTo(i2));  // 0 -> 두 객체가 가진 값이 같으므로 0. i2가 더 크면 -1, i가 더 크면 1
    System.out.println(i.toString());  // 100 -> 문자열로 출력(toString() 메서드 사용 안해도 println 메서드는 자동으로 문자열로 출력해준다)

기본형(primitive) vs. 래퍼 클래스(wrapper class)

기본형(primitive)래퍼클래스(wrapper class)
null 불가null 허용
JVM stack 메모리에 저장된다 → 접근이 쉽고 빠르다.JVM heap 메모리에 저장된다 → 비교적 메모리 접근 속도가 느리다.
변수 값을 간편하게 선언할 수 있다. 대용량 계산을 빠르게 처리할 수 있다.프로그램이 객체지향적이 되도록 돕는다.
값을 그대로 저장하며, 값의 변경이 가능하다.저장된 값을 변경할 수 없다. 변경하려는 값이 든 인스턴스를 새로 생성하여, 새 인스턴스의 주소값만 참조할 수 있다.
Collection Framework 데이터 구조는 기본형을 저장할 수 없다.Collection Framework 데이터 구조는 객체를 저장하므로 래퍼 클래스를 사용할 수 있다.
Generics 타입으로 들어갈 수 없다.Generics 타입으로 들어갈 수 있다.

[참고]

https://www.geeksforgeeks.org/wrapper-classes-java/?ref=rp

https://www.geeksforgeeks.org/java-i-o-operation-wrapper-class-vs-primitive-class-variables/

https://shanepark.tistory.com/449

<자바의 정석 - 기초편>

profile
🔥

0개의 댓글