java/코드 리뷰
14. sort - (1) Contact Demo (비교 메서드 재정의)
Astaroth아스
2020. 4. 24. 12:09
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
|
package sort;
public class Contact implements Comparable<Contact> {
private int no;
private String name;
private String tel;
private String email;
public Contact() {
}
public Contact(int no, String name, String tel, String email) {
super();
this.no = no;
this.name = name;
this.tel = tel;
this.email = email;
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
/*
이 객체와 다른 Contact를 비교하는 메서드를 재정의
번호(no)를 기준으로 비교하는 경우
이 객체의 번호가 다른 객체의 번호보다 크면 0보다 큰 값을 반환
이 객체의 번호와 다른 객체의 번호가 같으면 0 반환
이 객체의 번호가 다른 객체의 번호보다 작으면 0보다 작은 값 반환
*/
// public int compareTo(Contact other) {
// return this.no - other.no;
//
// }
/*
이 객체와 다른 Contact를 비교하는 메서드 재정의
이름(name)을 기준으로 비교하는 경우
이름은 문자열.
String에는 다른 String과 비교하는 compartTo(String o)가 이미 구현되어 있음
String에 구현된 compareTo(String o)를 사용해서
이 객체 이름과 다른 Contact 객체의 이름을 비교
*/
@Override
public int compareTo(Contact other) {
return this.name.compareTo(other.name);
}
}
|