Notice
Recent Posts
Recent Comments
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

DeFacto-Standard IT

[Java] Wrapper Class 본문

Java/Useful Classes

[Java] Wrapper Class

defacto standard 2017. 10. 2. 19:11

Primitive Type이 객체로서 다뤄져야 할 때가 있다.

매개변수로 객체를 요구할 때(Generic과 함께)

기본형이 아닌 객체로 저장해야할 때

객체간 비교가 필요할 때


등이 해당한다.


Wrapper Class는 Primitive와 Object간의 변환을 쉽게하도록 지원하는 클래스이다.


Wrapper Class의 생성자는 매개변수로 문자열이나 각 자료형의 값들을 인자로 받는다.


Primitive Type

Wrapper Class

Constructor

boolean

Boolean

Boolean(boolean value)

Boolean(String s)

char

Character

Character(char value)

byte

Byte

Byte(byte value)

Byte(String s)

short

Short

Short(short value)

Short(String s)

int

Integer

Integer(int value)

Integer(String s)

long

Long

Long(long value)

Long(String s)

float

Float

Float(double value)

Float(float value)

Float(String s)

double

Double

Double(double value)

Double(String s)


equals(), toString() Methods

Wrapper는 모두 equals()가 오버라이딩 되어있어서, 주소값이 아닌 객체가 가지고 있는 값을 기준으로 비교한다.

또한 toString() 역시도 오버라이딩 되어있어서, 가지고 있는 값을 문자열로 반환한다.


String to Primitive/Wrapper Methods

Wrapper는 String값을 Primitive혹은 Wrapper로 변환 시키는 메서드를 가지고 있다.

String -> Primitive

String -> Wrapper

byte b = Byte.parseByte("100");

short s = Short.parseShort("100");

int i = Integer.parseInt("100");

long l = Long.parseLong("100");

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

double d = Double.parseDouble("3.14");

Byte b = Byte.valueof("100");

Short s = Short.valueOf("100");

Integer i = Integer.valueOf("100");

Long l = Long.valueOf("100");

Float f = Float.valueOf("3.14");

Double d = Double.valueOf("3.14");



AutoBoxing

반환값이 Primitive Type일 때와 Wrapper 클래스일 때의 차이가 없도록 지원하는 기능.

따라서 구분없이 valueOf()를 쓸 수 있어 개발자가 편하게 개발이 가능하다.

굳이 비교하자면 valueOf()가 처리할 것이 더 많아져 조금 더 느리다는 것이다.


int i = Integer.parseInt("100");

int i = Integer.valueOf("100");

위 2개 문장의 차이는 속도외에는 없다. valueOf()가 함수의 네이밍 면에서 구분하기가 더 쉽다.



Radix (String with n Radix to Integer)

인자로 넘긴 문자열이 10진법이 아니라 다른 진법으로 표현된 경우에도 이를 변환시킬 수 있다.

인자로 넘긴 값을 특정한 진수로 보고, 2번째 인자를 통해 n진법이라고 명시할 수 있다.

진법을 생략한다면 10진법으로 간주한다.

int i4 = Integer.parseInt("100", 2); // 100(2) = 4(10)

int i5 = Integer.parseInt("100", 8); // 100(8) = 64(10)

int i6 = Integer.parseInt("100", 16); // 100(16) = 256(10)

int i7 = Integer.parseInt("FF"); // NumberFormatException


* 10진수(int) to 2진수(String)

String binaryString = Integer.toBinaryString(int a);



'Java > Useful Classes' 카테고리의 다른 글

[Java] Math Class  (0) 2017.10.02
[Java] StringBuffer Class  (0) 2017.10.02
[Java] String Class  (0) 2017.10.02
[Java] Object Class  (0) 2017.10.02
Comments