래퍼 클래스
2022. 6. 27. 22:35ㆍJava
◎ 래퍼 클래스
-> 기본형 값을 감싸는 클래스로 기본형 값이 아닌 객체로 저장할 때, 객체 간 비교가 필요할 때 등의 경우에 래퍼 클래스를 통해 기본형 값을 객체로 변환하여 작업을 수행할 수 있다.
-> 사용 예
public class WrapperEx1 {
public static void main(String[] args) {
Integer i = new Integer(100);
Integer i2 = new Integer(100);
System.out.println("i == i2 : " + (i==i2));
System.out.println("i.equals(i2) : " + (i.equals(i2)));
System.out.println("i.compareTo(i2) : " + i.compareTo(i2));
System.out.println("i.toString() : " + i.toString());
System.out.println("MAX_VALUE = " + Integer.MAX_VALUE);
System.out.println("MIN_VALUE = " + Integer.MIN_VALUE);
System.out.println("SIZE = " + Integer.SIZE + "bits");
System.out.println("BYTES = " + Integer.BYTES + "bytes");
System.out.println("TYPE = " + Integer.TYPE);
}
}
-> 결과
☞ 래퍼 클래스에는 equals()가 오버라이딩되어 있기 때문에 객체의 값을 비교한다. 따라서 i.equals(i2)의 결과는 true가 된다.
☞ 래퍼 클래스에는 toString()도 오버라이딩되어 있다.
◎ 문자열을 숫자로 변환
-> 문자열을 기본형으로 변환한느 것과 문자열을 래퍼 클래스로 변환하는 것에는 약간의 차이가 있다.
문자열 -> 기본형
byte b = Byte.parseByte("1");
short s = Short.parseShort("1");
int i = Integer.parseInt("1");
long l = Long.parseLong("1");
float f = Float.parseFloat("1.1");
double d = Double.parseDouble("1.1");
문자열 -> 래퍼 클래스
Byte b = Byte.valueOf("1");
Short s = Short.valueOf("1");
Integer i = Integer.valueOf("1");
Long l = Long.valueOf("1");
Float f = Float.valueOf("1.1");
Double d = Double.valueOf("1.1");
◎ 오토박싱, 언박싱
-> 오토박싱은 기본형을 래퍼 클래스로 자동으로 변환하는 것이다.
-> 언박싱은 래퍼 클래스를 기본형으로 변환하는 것이다.
int i = 7;
Integer ii = new Integer(7);
int sum = i + ii
☞ 위의 코드에서 i는 기본형, ii는 래퍼 클래스이다. 컴파일러가 자동으로 형변환하는 코드를 추가하여 기본형인 i와 래퍼 클래스인 ii간의 연산이 가능하도록 해준다.
★ 참고 및 출처
자바의 정석
'Java' 카테고리의 다른 글
컬렉션 프레임워크 - ArrayList (0) | 2022.06.29 |
---|---|
컬렉션 프레임워크 - List, Set, Map (0) | 2022.06.29 |
인터페이스 (0) | 2022.05.27 |
추상 클래스 (0) | 2022.05.26 |
다형성(2) (0) | 2022.05.26 |