TreeSet自定义排序

import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;

/**
 * .写一个应用程序,让美国,中国,俄罗斯,加拿大,巴西这五个国家按面积进行排序,
 * 其中美国950万平方公里,中国960万平方公里,俄罗斯1200万平方公里,加拿大990平方公里,
 * 巴西550万平方公里(要求:必须用集合来做)
 * @author 够潮
 *
 */
public class Demo6 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		/**
		 * 初始化数据
		 */
		Country country = new Country("中国",960);
		Country country2 = new Country("美国",950);
		Country country3 = new Country("俄罗斯",1200);
		Country country4 = new Country("加拿大",990);
		Country country5 = new Country("巴西",550);
		/**
		 * 填充数据
		 */
		Set<Country> set = new TreeSet<Country>();
		set.add(country);
		set.add(country2);
		set.add(country3);
		set.add(country4);
		set.add(country5);
		/**
		 * 遍历数据
		 */
		Iterator it = set.iterator();
		while(it.hasNext()){
			Country c  = (Country) it.next();
			System.out.println("国家:  " +c.name + "    国家面积"+c.area);
		}
		
		

	}

}

class Country implements Comparable{
	
	/**
	 * 面积
	 */
	public int area;
	/**
	 * 名称
	 */
	public String name;
	public Country( String name ,int area) {
		super();
		this.area = area;
		this.name = name;
	}
	public int compareTo(Object o) {
		Country country = (Country) o;
		//return this.area - country.area;//排序从小到大
		return -(this.area - country.area);//排序从大到小
	}
	
	
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值