Question 8.2: B. Comparable Interface
• Comparable Interface is used to compare two objects. In this problem, you'll create a class that
implements the comparable interface and use it to sort an array of objects.
• Create a Player class with 2 fields: name of String Type and score of integer type.
• Define proper constructor to set the attributes value
• Modify the Player class to implement the Comparable interface
• Given an array of n Player objects and sort them in order of decreasing score; if 2 or more players
have the same score, sort those players alphabetically by name. To do this, you must override the
compareTo ( Player b ) method of comparable interface in the player class.
Input Format
The first line contains an integer, n, denoting the number of players.
Each of the n subsequent lines contains a player's name and score, respectively.
Output Format
Print each sorted element in the format: namescore
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
Solution:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class lab8qus2 {
public static void main(String[] args) {
ArrayList<Player> p = new ArrayList<>();
Scanner obj = new Scanner(System.in);
int a = obj.nextInt();
for (int i = 0; i < a; i++) {
String x = obj.next();
int y = obj.nextInt();
p.add(new Player(x, y));
}
Collections.sort(p);
for (Player pt : p) {
System.out.println(pt.name + " " + pt.score);
}
}
}
class Player implements Comparable<Player> {
String name;
int score;
Player(String name, int score) {
this.name = name;
this.score = score;
}
public int compareTo(Player pt) {
if (score == pt.score)
return 0;
else if (score < pt.score)
return 1;
else
return -1;
}
}