[HackerRank] JAVA Comparator

OOSEDUS·2025년 3월 11일
0

해커랭크

목록 보기
3/13
post-thumbnail

문제

Comparators are used to compare two objects. In this challenge, you'll create a comparator and use it to sort an array.

The Player class is provided for you in your editor. It has fields: a String and a integer.

Given an array of Player objects, write a comparator that sorts them in order of decreasing score; if or more players have the same score, sort those players alphabetically by name. To do this, you must create a Checker class that implements the Comparator interface, then write an int compare(Player a, Player b) method implementing the Comparator.compare(T o1, T o2) method.

Input Format
Input from stdin is handled by the locked stub code in the Solution class.

The first line contains an integer, , denoting the number of players.
Each of the subsequent lines contains a player's and , respectively.

Constraints
players can have the same name.
Player names consist of lowercase English letters.

Output Format
You are not responsible for printing any output to stdout. The locked stub code in Solution will create a Checker object, use it to sort the Player array, and print each sorted element.

Sample Input

5
amy 100
david 100
heraldo 50
aakansha 75
aleksa 150

Sample Output

aleksa 150
amy 100
david 100
aakansha 75
heraldo 50

첫번째 시도 : Compile Error

class Checker implements Comparator {
    
    public int compare(Player A, Player B){
        if (A.score > B.score) return 1;
        else if (A.score == B.score) {
            if (A.name > B.name) {
                return 1;
            } else return -1;
        } else {
            return -1;
        }
    }
}

Compile time error
Solution.java:2: error: Checker is not abstract and does not override abstract method compare(Object,Object) in Comparator
class Checker implements Comparator {
^
Solution.java:7: error: bad operand types for binary operator '>'
if (A.name > B.name) {
^
first type: String
second type: String
Note: Solution.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
2 errors

문제 원인 :

  • Comparator는 제네릭 인터페이스이므로, Comparator로 명시해야함.
  • Java에서는 String을 > 또는 < 연산자로 비교할 수 없음.
    String 비교는 .compareTo()를 사용해야 함.
  • 불필요한 if-else 존재

두번째 시도 : Success

class Checker implements Comparator<Player>{
    
    @Override
    public int compare(Player p1, Player p2) {
        if (p1.score != p2.score) {
            return p2.score - p1.score;
        }
        return p1.name.compareTo(p2.name);
    }
}

알아야할 개념

  • Comparator는 제네릭 인터페이스라서 사용한 타입을 명시해줘야한다.
  • 내림차순 조건으로 인해서 p1이 더 큰 경우 p2보다 뒤로 가야하기 때문에 반대로 되어야함
  • Arrays.sort()의 동작 방식 :
    1) Arrays.sort()는 내부적으로 정렬 알고리즘을 실행하며 여러 번 compare(a, b)를 호출함.
    2) compare(a, b)의 반환값에 따라 두 요소의 순서를 바꿈.
    - 음수 → 순서 유지
    - 0 → 변경 없음
    - 양수 → 위치 변경
    3) 반복적으로 compare()를 호출하면서 전체 배열을 정렬함.
profile
성장 가능성 만땅 개발블로그

0개의 댓글