TreeSet自然排序和指定排序



package com.boyong;

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

public class Set {

	public static void main(String[] args) {
		
		//自然排序
		natrueSort();
		
		//指定排序
		fingerMustSort();
		
	}
	
	private static void fingerMustSort() {

		TreeSet<ProfitAddLoss> set = new TreeSet<>();
		//(收入,成本,利润): 指定利润升序排列
		set.add(new ProfitAddLoss(100, 50, 50));
		set.add(new ProfitAddLoss(100, 80, 20));
		set.add(new ProfitAddLoss(100, 60, 40));
		set.add(new ProfitAddLoss(100, 30, 70));
		
		Iterator<ProfitAddLoss> iterator = set.iterator();
		while(iterator.hasNext()) {
			ProfitAddLoss obj = iterator.next();
			System.out.println(obj.liRun);
		}
		
	}

	private static void natrueSort() {

		TreeSet<Object> set = new TreeSet<>();
		boolean add = set.add(1);
		boolean add2 = set.add(1);
		boolean add3 = set.add(2);
		boolean add4 = set.add(3);
		
		System.out.println(add);
		System.out.println(add2);//插入失败
		System.out.println(add3);
		System.out.println(add4);
		
		Iterator<Object> iterator = set.iterator();
		while(iterator.hasNext()) {
			Object obj = iterator.next();
			System.out.println(obj);
		}
		
	}

	@SuppressWarnings("all")
	private static class ProfitAddLoss implements Comparable<ProfitAddLoss>{//损益
		
		private double shouRu;//收入
		private double chengBen;//成本
		private double liRun;//利润
		
		@Override
		public int compareTo(ProfitAddLoss o) {
			if (this.liRun <= o.liRun) {//利润多的靠前
				return 1;
			}
			return -1;
		}
		
		public ProfitAddLoss(double shouRu, double chengBen, double liRun) {
			super();
			this.shouRu = shouRu;
			this.chengBen = chengBen;
			this.liRun = liRun;
		}
		public double getShouRu() {
			return shouRu;
		}
		public void setShouRu(double shouRu) {
			this.shouRu = shouRu;
		}
		public double getChengBen() {
			return chengBen;
		}
		public void setChengBen(double chengBen) {
			this.chengBen = chengBen;
		}
		public double getLiRun() {
			return liRun;
		}
		public void setLiRun(double liRun) {
			this.liRun = liRun;
		}
		
	}
	
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值