Let's take a example.
The Country has String type name, int type gold, silver, bronze. This class represent how many medal each country get in the Olympic games. We need sort this by gold in descending order. If the the number of gold medal is the same, by silver. If the number of silver medal is the same, by bronze.
If all three medals have equal number each, then order by country name in ascending order.
int compareTo(T o)
Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
In our case, we need to sort by descending in medal count, and ascending in country name.
Based on the requirement, it has to be adjusted.
class Country implements Comparable{
public String name;
public int gold;
public int silver;
public int bronze;
public Country(String n, int g, int s, int b) {
name = n;
gold = g;
silver = s;
bronze = b;
}
// ascending order
public int compareTo(Object o) {
Country co = (Country)o;
if (this.gold == co.gold) {
if (this.silver == co.silver) {
if (this.bronze == co.bronze) {
return this.name.compareTo(co.name);
} else if (this.bronze > co.bronze)
return -1;
else
return 1;
} else if (this.silver > co.silver)
return -1;
else
return 1;
} else if (this.gold > co.gold) {
return -1;
} else
return 1;
}
}
public class MyCode {
public static void main (String[] args) throws java.lang.Exception {
ArrayList
MyCode code = new MyCode();
code.create(array);
Collections.sort(array);
for (int i=0;i
System.out.println(con.name + " " + con.gold + " " + con.silver + " " + con.bronze);
}
}
public void create(ArrayList
array.add(new Country("KOR", 3,1,1));
array.add(new Country("AUS", 2,1,1));
array.add(new Country("GRE", 0,0,1));
array.add(new Country("ZEN", 0,0,1));
array.add(new Country("ENG", 0,0,1));
}
}
It will print the output below.
KOR 3 1 1
AUS 2 1 1
ENG 0 0 1
GRE 0 0 1
ZEN 0 0 1
No comments:
Post a Comment