https://www.acmicpc.net/problem/10825
Java에서 클래스로 정렬하는 방법을 보여주는 항목입니다.
Java에서 정렬하는 방법은 2가지가 있는데요,
1. 클래스 안에서 정렬
- class뒤 implements Comparable 해주기.
- Override로 compareTo해주기.
@Override public int compareTo(Student other) {
▼아래 코드
public static class Student implements Comparable<Student>{
String name;
int kor;
int eng;
int math;
public Student(String n, int k, int e, int m) {
name = n;
kor = k;
eng = e;
math = m;
}
@Override
public int compareTo(Student other) {
// TODO Auto-generated method stub
if(this.kor == other.kor && this.eng == other.eng
&& this.math == other.math)
return this.name.compareTo(other.name);
if(this.kor == other.kor && this.eng == other.eng)
return Integer.compare(other.math, this.math);
if(this.kor == other.kor)
return Integer.compare(this.eng, other.eng);
return Integer.compare(other.kor, this.kor);
}
}
2. Collections.sort 함수 내부에서 정의.
- new Comparator
- Override로 compare해주기
@Override public int compare(Node o1, Node o2)
Collections.sort(list, new Comparator<Node>() {
@Override
public int compare(Node o1, Node o2) {
if( (o1.kukScore == o2.kukScore) && (o1.EngScore == o2.EngScore) && (o1.MathScore == o2.MathScore)) {
return o1.name.compareTo(o2.name);
} else if( (o1.kukScore == o2.kukScore) && (o1.EngScore == o2.EngScore) ) {
return Integer.compare(o2.MathScore, o1.MathScore);
} else if( (o1.kukScore == o2.kukScore) ) {
return Integer.compare(o1.EngScore, o2.EngScore);
}
return Integer.compare(o2.kukScore, o1.kukScore);
}
});
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int N = input.nextInt();
ArrayList<Student> Stulist = new ArrayList<Student>();
for(int n = 0; n < N; n++) {
String S = input.next();
int kor = input.nextInt();
int eng = input.nextInt();
int math = input.nextInt();
Stulist.add(new Student(S, kor, eng, math));
}
Collections.sort(Stulist);
for(int i = 0; i < N; i++)
System.out.println(Stulist.get(i).name);
}
public static class Student implements Comparable<Student>{
String name;
int kor;
int eng;
int math;
public Student(String n, int k, int e, int m) {
name = n;
kor = k;
eng = e;
math = m;
}
@Override
public int compareTo(Student other) {
// TODO Auto-generated method stub
if(this.kor == other.kor && this.eng == other.eng
&& this.math == other.math)
return this.name.compareTo(other.name);
if(this.kor == other.kor && this.eng == other.eng)
return Integer.compare(other.math, this.math);
if(this.kor == other.kor)
return Integer.compare(this.eng, other.eng);
return Integer.compare(other.kor, this.kor);
}
}
}