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;
}
}
}
TreeSet自然排序和指定排序
最新推荐文章于 2024-07-24 21:47:59 发布