728x90
반응형
[문제2] Student클래스가 Comparable인터페이스를 구현해서, list를 총점(total) 내림차순으로 정렬되도록 하는 예제입니다.
아래의 코드를 완성하세요.
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
|
package testAl;
import java.util.*;
class SungJukEx2 {
public static void main(String[] args) {
ArrayList<Student1> list = new ArrayList<Student1>();
// 이름, 반, 번호, 국어, 수학, 영어
list.add(new Student1("남궁성", 3,2,100,100,100));
list.add(new Student1("왕자바", 3,1,90,100,80));
list.add(new Student1("자바왕", 3,3,70,100,100));
list.add(new Student1("킹왕짱", 1,2,100,60,90));
list.add(new Student1("자바짱", 1,1,100,100,100));
list.add(new Student1("최고수", 1,3,100,80,60));
list.add(new Student1("홍길동", 2,1,50,80,100));
list.add(new Student1("일지매", 2,3,70,80,100));
list.add(new Student1("변강쇠", 2,4,80,80,85));
list.add(new Student1("이원구", 2,2,90,90,90));
Collections.sort(list);
printList(list);
}
public static void printList(List<Student1> list) {
System.out.println("이름\t학년\t반\t국어\t수학\t영어\t총점 ");
System.out.println("====================================================");
for(Student1 s : list) {
System.out.println(s);
}
System.out.println("====================================================");
}
}
class Student1 implements Comparable<Student1> {
String name = "";
int classNo = 0;
int studentNo = 0;
int koreanScore = 0;
int mathScore = 0;
int englishScore = 0;
int total = 0;
Student1(String name, int classNo, int studentNo, int koreanScore,
int mathScore, int englishScore) {
this.name = name;
this.classNo = classNo;
this.studentNo = studentNo;
this.koreanScore = koreanScore;
this.mathScore = mathScore;
this.englishScore = englishScore;
total = koreanScore + mathScore + englishScore;
}
public String toString() {
return name + "\t"
+ classNo + "\t"
+ studentNo + "\t"
+ koreanScore + "\t"
+ mathScore + "\t"
+ englishScore + "\t"
+ total + "\t";
}
@Override
public int compareTo(Student1 obj) {
// 코드를 완성하세요.
// 자신의 합계와 비교하려는 학생의 합계를 빼는 거에요.
// 뺄셈으로 두 값중에서 어느값이 큰지 알 수 있습니다.
// 두 값의 차이가 0이면 같은거고 두값의 차이가 양수면 앞의 값이 큰거고
// 음수면 뒤의 값이 큰거죠.
return obj.total-total;
}
} // end of class Student
|
[실행 결과]
- Comparable에 대해서 알아보자
[정렬]
- 내림차순, 오름차순 정렬
* Arrays.sort() 정렬
- 한글순 > 소문자 > 대문자 > 숫자 순으로 정렬된다.
* Collections.sort(); => 오름차순 정렬
* Collections.reverse(); => 내림차순 정렬
- 다른기준으로 정렬하고 싶을때
* Comparable 인터페이스 활용
- 위 내용에서 활용내용을 확인할 수 있다.
- 클래스에 implement로 인터페이스를 구현하여 쓸 수 있다.
- compareTo 메소드를 오버라이드 하여 다른 기준으로 정렬할 수 있다.
728x90
반응형
'알고리즘 > 남궁성 자바 1000제' 카테고리의 다른 글
[Java1000제] 성적처리 4 - 전교등수 계산 (0) | 2021.03.02 |
---|---|
[Java1000제] 성적처리 3 - Comparator를 이용한 정렬 (0) | 2021.02.12 |
[Java1000제] 성적처리 1 - Student클래스 만들기 (0) | 2021.02.06 |