IT/자바

Wrapper 클래스

Beautifulkim 2018. 4. 30. 11:33

사용목적 : 정수형으로 변환해야할 경우


package mymain;


import java.util.ArrayList;


public class MyMain_Wrapper {


public static void main(String[] args) {

//★★★★★ 아주 중요한 객체

//Collection객체(데이터를 저장관리하는 객체)

//자바의 모든 객체를 저장

ArrayList list = new ArrayList();

int n = 10;//이건 객체라 안부르고 변수라 부름

// Auto-Boxing(자동포장) <= JDK5.0이후부터

list.add(n);

list.add(3.14);

// list.add(new Integer(n));

// list.add(new Double(3.14));

//int 형=>객체화

Integer nOb = new Integer(n); //명시적

Integer nOb1 = n; // Auto-Boxing

int n1 = nOb.intValue();//

int n2 = nOb;// Auto Unboxing(자동포장해체

float f = nOb; // nOb.floatValue()

double d = nOb; // nOb.doubleValue()


}


}




[ 아래 출처 : https://blog.naver.com/shumin/220350807800 ]



# 사실 Wrapper인 클래스는 존재하지 않는다. 다만 8개의 기본 데이터를 객체 형식으로 다루기 위해 JDK에 의해 지원된 클래스를 통칭하여 Wrapper 클래스라 말한다.


 


# 3, 'a', 3.5 는 데이터값도, 객체도 아니다.


# java.lang 패키지에서 모두 제공한다.


 

1
2
3
4
Integer i = new Integer(10);
Character ch = new Character('c');
Float f = new Float(3.14);
Boolean bool = new Boolean(true);
cs


 

  • Wrapper 클래스의 활용

 

 


- Wrapper 클래스의 객체에 들어 있는 해당 데이터 값을 알아내기 위해서는 다음과 같은 메소드를 사용한다.


 

1
2
3
4
5
6
7
8
9
10
11
        Integer i = new Integer(10);
        int ii = i.intValue();    // ii = 10
        
        Character c = new Character('c');
        char cc = c.charValue();    // cc = 'c'
        
        Float f = new Float(3.14);
        float ff = f.floatValue();    // ff = 3.14
        
        Boolean b = new Boolean(true);
        boolean bb = b.booleanValue();    // bb = true
cs


문자열을 기본 데이터 타입으로 변환!!!


 

1
2
3
int i = Integer.parseInt("12");    // i = 12

boolean b = Boolean.parseBoolean("true");    // b = true

float f = Float.parseFloat("3.14");    // f = 3.14
cs


- 위 메소드들은 static 타입으로 Wrapper 객체를 생성하지 않고 클래스의 이름으로 바로 메소드를 호출한다.


# 기본 데이터 타입을 문자열로 변환


 

1
2
3
4
5
        String s1 = Integer.toString(12);        // 정수 12를 문자열 "12"로 변환
        String s2 = Integer.toHexString(12);   // 정수 12를 16진수의 문자열 "c"로 변환
        String s3 = Boolean.toString(true);    // boolean값 true를 문자열 "true"로 변환
        String s4 = Float.toString(3.14f);       // 실수 3.14를 문자열 "3.14"로 변환
        String s5 = Character.toString('c');    // 문자 'c'를 문자열 "c"로 변환
cs


 

  • boxing & unboxing

 

- 기본 데이터 타입을 Wrapper 클래스로 변환하는 것을 boxing(박싱)이라고 하고, 반대의 경우를 unboxing(언박싱)이라 한다.


 


- JDK 1.5부터 박싱, 언박싱은 자동으로 된다.