어제로 중간고사가 끝났다
다시 시작하자!
래퍼(Wrapper)클래스
객체지향 개념에서는 모든 것이 객체로 다루어져야 한다
하지만, 자바에서는 8개의 기본형을 객체로 다루지 않았고 그 대신 보다 높은 성능을 얻을 수 있었다.
때로는, 기본형 변수도 어쩔 수 없이 객체로 다뤄야 하는 경우가 있다
ex)
- 매개변수로 객체를 요구할 때
- 기본형 값이 아닌 객체로 저장해야 할 때,
- 객체 간의 비교가 필요할 때
등등
--> 기본형 값들을 객체로 변환하여 작업을 수행해야 함, 이 때 사용되는 것이 래퍼(Wrapper)클래스
Wrapper클래스는 매개변수로 문자열이난 각 자료형의 값들을 인자로 받는다
( 각 자료형에 알맞게 사용해야 함 )
ex)
Integer i = new Integer(1.0); X
Integer i = new Integer(10); O
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
class WrapperEx1 {
public static void main(String[] args) {
Integer i = new Integer(100);
Integer i2 = new Integer("100");
System.out.println(i==i2);
System.out.println(i.equals(i2));
System.out.println(i.compareTo(i2));
System.out.println(i.toString());
System.out.println(i2.toString());
// Wrapper클래스인 Integer클래스의 멤버 호출
System.out.println(Integer.MAX_VALUE);
System.out.println(Integer.MIN_VALUE);
System.out.println(Integer.SIZE + "bits");
System.out.println(Integer.BYTES);
System.out.println(Integer.TYPE);
}
}
|
cs |
출력
false
true
0
100
100
2147483647
-2147483648
32bits
4
int
Wrapper클래스는 equals()가 오버라이딩되어 있어서 주소값이 아닌 객체가 가지고 있는 값을 비교
그래서 실행결과에 equals()가 true로 출력됨
그래서 compareTo()를 제공
수를 비교하는 메소드, i의 값이 i2와 같으면 0, i2보다 크면 1, i2보다 작으면 -1반환
문자열을 숫자로 변환하기
타입.parse타입(String s) -> 기본형으로 변환
타입.valueOf(String s) -> Wrapper클래스로 변환
|
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
32
33
34
35
36
37
|
class WrapperEx2 {
public static void main(String[] args) {
int i = new Integer("100").intValue(); // Integer -> int
int i2 = Integer.parseInt("100");
Integer i3 = Integer.valueOf("100");
// 다른 진법의 숫자를 변경
int i4 = Integer.parseInt("100", 2); // 2진수 -> 10진수
int i5 = Integer.parseInt("100", 8); // 8진수 -> 10진수
int i6 = Integer.parseInt("100", 16); // 16진수 -> 10진수
int i7 = Integer.parseInt("FF", 16); // 16진수 -> 10진수
// int i8 = Integer.parseInt("FF"); // 오류, NumberFormatException 발생
Integer i9 = Integer.valueOf("100", 2);
Integer i10 = Integer.valueOf("100", 8);
Integer i11 = Integer.valueOf("100", 16);
Integer i12 = Integer.valueOf("FF", 16);
// Integer i13 = Integer.valueOf("FF"); // 오류, NumberFormatException 발생
System.out.println(i);
System.out.println(i2);
System.out.println(i3);
System.out.println("다른 진법의 숫자");
System.out.println("100(2) -> "+i4);
System.out.println("100(8) -> "+i5);
System.out.println("100(16) -> "+i6);
System.out.println("FF(16) -> "+i7);
System.out.println("100(2) -> "+i9);
System.out.println("100(8) -> "+i10);
System.out.println("100(16) -> "+i11);
System.out.println("FF(16) -> "+i12);
}
}
|
cs |
출력
100
100
100
다른 진법의 숫자
100(2) -> 4
100(8) -> 64
100(16) -> 256
FF(16) -> 255
100(2) -> 4
100(8) -> 64
100(16) -> 256
FF(16) -> 255
오토박싱 / 언박싱
이전에는 기본형과 참조형 간의 연산이 불가능해서 래퍼클래스로 기본형을 객체로 만들어 연산해야 했다
그러나, 이제는 기본형과 참조형 간의 연산이 가능하다
-> 컴파일러가 자동으로 변환하는 코드를 넣어줌 ( int sum = i + iObj.intValue(); )
기본형 값 -> 래퍼클래스의 객체 : 오토박싱
래퍼클래스의 객체 -> 기본형 값 : 언박싱
|
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
|
class WrapperEx3 {
public static void main(String[] args) {
int i = 10;
// 기본형 -> Wrapper클래스
Integer intg = (Integer)i; // Integer intg = Integer.valueOf(i);
Object obj = (Object)i; // Object obj = (Object)Integer.valueOf(i);
Long lng = 100L; // Long lng = new Long(100L);
int i2 = intg + 10; // 기본형과 참조형 연산 가능
long l = intg + lng; // 참조형 간의 연산도 가능
Integer intg2 = new Integer(20);
int i3 = (int)intg2; // 참조형 -> 기본형
Integer intg3 = intg2 + i3; // 기본형과 참조형 연산 가능
System.out.println("i = " + i);
System.out.println("intg = " + intg);
System.out.println("obj = " + obj);
System.out.println("lng = " + lng);
System.out.println("intg + 10 = " + i2);
System.out.println("intg + lng = " + l);
System.out.println("intg2 = " + intg2);
System.out.println("i3 = " + i3);
System.out.println("intg2 + i3 = " + intg3);
}
}
|
cs |
출력
i = 10
intg = 10
obj = 10
lng = 100
intg + 10 = 20
intg + lng = 110
intg2 = 20
i3 = 20
intg2 + i3 = 40
유용한 클래스
java.util.Objects클래스
Object클래스의 보조 클래스로 Math클래스처럼 모든 메소드가 'static'
객체의 비교, 널 체크에 유용
isNull()
해당 객체가 null인지 확인, null -> true, null x -> false
nonNull()
isNull()의 반대
requireNonNull()
객체가 null이면, NullPointerException을 발생시킴
두 번째 매개변수로 지정하는 문자열은 예외 메세지
|
1
2
3
4
|
void setName(String name) {
this.name = Objects.requireNonNull(name, "name must not be null");
}
|
cs |
compare()
대소비교
두 비교대상이 같으면 0, 크면 양수, 작으면 음수 반환
|
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
32
33
34
35
36
37
38
|
import java.util.Arrays;
import java.util.Comparator;
import java.util.Objects;
class ObjectsTest {
public static void main(String[] args) {
String[][] str2D = new String[][] {{"aaa","bbb"},{"AAA","BBB"}};
String[][] str2D_2 = {{"aaa","bbb"},{"AAA","BBB"}};
System.out.print("str2D = {");
for(String[] tmp : str2D)
System.out.print(Arrays.toString(tmp));
System.out.println("}");
System.out.print("str2D_2 = {");
for(String[] tmp : str2D_2)
System.out.print(Arrays.toString(tmp));
System.out.println("}");
System.out.println("isNull(null) = " + Objects.isNull(null));
System.out.println("nonNull(null) = " + Objects.nonNull(null));
System.out.println("hashCode(null) = " + Objects.hashCode(null));
System.out.println("toString(null) = " + Objects.toString(null));
System.out.println("toString(null, \"\") = "
+ Objects.toString(null, ""));
Comparator c = String.CASE_INSENSITIVE_ORDER; // 대소문자 구분안하는 비교
System.out.println("compare(\"aa\",\"bb\") = "
+ Objects.compare("aa","bb",c));
System.out.println("compare(\"bb\",\"aa\") = "
+ Objects.compare("bb","aa",c));
System.out.println("compare(\"ab\",\"AB\") = "
+ Objects.compare("ab","AB",c));
}
}
|
cs |
출력
str2D = {[aaa, bbb][AAA, BBB]}
str2D_2 = {[aaa, bbb][AAA, BBB]}
isNull(null) = true
nonNull(null) = false
hashCode(null) = 0
toString(null) = null
toString(null, "") =
compare("aa","bb") = -1
compare("bb","aa") = 1
compare("ab","AB") = 0
java.util.Random클래스
난수를 얻는 방법은 두 가지가 있다
아래 두문장은 동등하다
- double randNum = Math.random();
- double randNum = new Random().nextDouble();
ex) 1~6사이의 정수를 나수로 얻고자 할때
- int num = (int)(Math.random() * 6) + 1;
- int num = new Random().nextInt(6) + 1;
Math.random()과 Random의 가장 큰 차이점은 종자값(seed)를 설정 할 수 있다는 것
Random클래스의 Random()생성자는 종자값을 현재시간으로 해서 실행할 때마다 얻는 난수가 달라짐
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
import java.util.Random;
class RandomEx1 {
public static void main(String[] args) {
// 둘 다 종자값을 1로 설정
Random rand = new Random(1);
Random rand2 = new Random(1);
System.out.println("= rand =");
for(int i=0; i<5; i++)
System.out.println(i + ":" + rand.nextInt());
System.out.println();
System.out.println("= rand2 =");
for(int i=0; i<5; i++)
System.out.println(i + ":" + rand2.nextInt());
}
}
|
cs |
출력
= rand =
0:-1155869325
1:431529176
2:1761283695
3:1749940626
4:892128508
= rand2 =
0:-1155869325
1:431529176
2:1761283695
3:1749940626
4:892128508
--> rand와 rand2가 같은 종자값을 사용하기 때문에 같은 값들을 얻음
|
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
32
33
34
|
import java.util.Random;
class RandomEx2 {
public static void main(String[] args) {
Random rand = new Random();
int[] number = new int[100];
int[] counter = new int[10];
for(int i=0; i<number.length; i++) {
// System.out.print(number[i] = (int)(Math.random() * 10));
// 0 <= x < 10 범위의 정수 x를 반환
System.out.print(number[i] = rand.nextInt(10));
}
System.out.println();
for(int i=0; i<number.length; i++)
counter[number[i]]++; //
for(int i=0; i<counter.length; i++)
System.out.println(i +"의 개수 :" + printGraph('#',counter[i])
+ " " + counter[i]);
}
public static String printGraph(char ch, int value) {
char[] bar = new char[value]; // counter[i]에 저장되어 있는 각 요소의크기만큼 char배열 생성
for(int i=0; i<bar.length; i++) // 생성된 배열의 크기만큼 '#'를 저장
bar[i] = ch;
return new String(bar); // 문자열로 반환
}
}
|
cs |
출력
0889936699147438609219987738216713858845496357848537363606340203453075167477986609803981918951144817
0의 개수 :######## 8
1의 개수 :########## 10
2의 개수 :### 3
3의 개수 :############ 12
4의 개수 :########## 10
5의 개수 :####### 7
6의 개수 :########### 11
7의 개수 :########### 11
8의 개수 :############### 15
9의 개수 :############# 13
|
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
32
33
34
35
36
37
|
import java.util.Arrays;
class RandomEx3 {
// getRand(int from, int to) - from~to 사이의 난수를 발생시키는 메소드
// fillRand(int[] arr, int from, int to) - arr배열에 from~to 사이의 난수값을 저장후 반환하는 메소드
// fillRand(int[] arr, int[] data) - data배열에 저장되어 있는 요소들을 랜덤으로 arr에 저장하는 메소드
public static int[] fillRand(int[] arr, int from, int to) {
for(int i=0; i<arr.length; i++) {
arr[i] = getRand(from, to);
}
return arr;
}
public static int[] fillRand(int[] arr, int[] data) {
for(int i=0; i<arr.length; i++) {
arr[i] = data[getRand(0,data.length-1)];
}
return arr;
}
public static int getRand(int from, int to) {
return (int)(Math.random() * (Math.abs(to-from)+1)) + Math.min(from, to);
}
public static void main(String[] args) {
for(int i=0; i<10; i++) {
System.out.print(getRand(5,10)+","); // 5~10사이의 난수
}
System.out.println();
int[] result = fillRand(new int[10], new int[] {2,3,7,5}); // 0~3 요소값을 랜덤으로 result에 저장
System.out.println(Arrays.toString(result));
}
}
|
cs |
출력
7,8,7,7,7,9,6,6,10,8,
[3, 3, 5, 5, 3, 5, 2, 7, 5, 3]
'아카이브 > 자바의 정석' 카테고리의 다른 글
| 11장 컬렉션 프레임워크 20201026 (0) | 2020.10.26 |
|---|---|
| 9장 java.lang패키지와 유용한 클래스 20201024 (0) | 2020.10.24 |
| 9장 java.lang패키지와 유용한 클래스 20201018 (0) | 2020.10.18 |
| 9장 java.lang패키지와 유용한 클래스 20201017 (0) | 2020.10.17 |
| 9장 java.lang패키지와 유용한 클래스 20201014 (0) | 2020.10.14 |