33,010
社区成员
发帖
与我相关
我的任务
分享
import java.util.Comparator;
import java.util.TreeSet;
import org.junit.Test;
/**
* 国家
*
*/
class Country{
private String name;
private int jin;
private int yin;
private int tong;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getJin() {
return jin;
}
public void setJin(int jin) {
this.jin = jin;
}
public int getYin() {
return yin;
}
public void setYin(int yin) {
this.yin = yin;
}
public int getTong() {
return tong;
}
public void setTong(int tong) {
this.tong = tong;
}
public Country(String name, int jin, int yin, int tong) {
super();
this.name = name;
this.jin = jin;
this.yin = yin;
this.tong = tong;
}
public Country() {
super();
}
@Override
public String toString() {
return "Country [国家=" + name + ", 金牌=" + jin + ", 银牌=" + yin
+ ", 铜牌=" + tong + "]";
}
}
/**
*自定义比较器
*
*/
class MyCompare implements Comparator<Country>{
public int compare(Country o1, Country o2) {
int jinCha=o1.getJin()-o2.getJin();
if(jinCha!=0){
return -jinCha;
}else{
int yinCha=o1.getYin()-o2.getYin();
if(yinCha!=0){
return -yinCha;
}else{
int tongCha=o1.getTong()-o2.getTong();
if(tongCha!=0){
return -tongCha;
}else{
return o1.getName().compareTo(o2.getName());
}
}
}
}
}
public class GoldSort {
public void sortAndPrint(){
TreeSet<Country> set=new TreeSet<Country>(new MyCompare());
Country usa=new Country("美国", 46, 29, 29);
Country cha=new Country("中国", 38, 27, 23);
Country us=new Country("英国", 29, 17, 19);
Country rus=new Country("俄罗斯", 24, 26, 32);
Country kor=new Country("韩国", 13, 8, 7);
Country gem=new Country("德国", 11, 19, 14);
Country fra=new Country("法国", 11, 11, 12);
Country ita=new Country("意大利", 8, 9, 11);
Country mag=new Country("匈牙利", 8, 4, 5);
Country aus=new Country("澳大利亚", 7, 16, 12);
//乱序加入
set.add(gem);
set.add(aus);
set.add(mag);
set.add(fra);
set.add(rus);
set.add(us);
set.add(ita);
set.add(cha);
set.add(usa);
set.add(kor);
System.out.println("输出金牌榜:");
for(Country c:set){
System.out.println(c);
}
}
@Test
public void test(){
this.sortAndPrint();
}
}