2020.02.22 TreeSet集合

bean包

package com.guoyun.bean;

/**
* ClassName:
* Function: ADD FUNCTION
* Reason: ADD REASON
*
* @author
* @Date
* @since Ver 1.1
*/
public class SnackBean implements Comparable<SnackBean>{
//编号
public String id;
//名称
public String name;
//价格
public String price;

 

@Override
public int compareTo(SnackBean o) {
double p1=Double.parseDouble(price);
double p2=Double.parseDouble(o.price);
//>0 从小到大排序
//<0 从大到小排序
if(id.equals(o.id)){
return 0;
}else if(p1>p2)
{
//1 从小到大排序 -1 从大到小排序
return 1;
}else{
return -1;
}
// return (int)(p1-p2);
}
}

******************************************************************************************************************************************

view包

package com.guoyun.view;

import com.guoyun.bean.SnackBean;

import java.io.Serializable;
import java.util.*;

/**
* ClassName:
* Function: ADD FUNCTION
* Reason: ADD REASON
*
* @author
* @Date
* @since Ver 1.1
*/
public class MainView {
public static TreeSet<String> set1 = new TreeSet();
public static AbstractSet<String> set2 = new TreeSet();
public static NavigableSet set3 = new TreeSet();
public static Cloneable set4 = new TreeSet<>();
public static Serializable set5 = new TreeSet<>();
public static AbstractCollection set6 = new TreeSet();
public static Set<String> set7 = new TreeSet();
public static Collection set8 = new TreeSet();
public static Iterable set9 = new TreeSet();
public static SortedSet set10 = new TreeSet();

public static void main(String[] args) {
//并非按照int类型从小到大排序 是按照数字前后顺序排序
// set7.add("1");
// set7.add("106");
// set7.add("2");
// set7.add("24");
//按照字母的顺序排序
// set7.add("a");
// set7.add("f");
// set7.add("s");
// set7.add("q");
//中文无法排序 乱序输出
//不允许添加空对象 List集合可以
//包装类和String(数字和字母)可以实现自动排序
set7.add("春");
set7.add("夏");
set7.add("秋");
set7.add("冬");
// for (String s : set7) {
// System.out.println(s);
// }
Set<SnackBean> set11=new TreeSet<>();
SnackBean ls=new SnackBean();
ls.id="123";
ls.name="跳跳糖";
ls.price="2.5";
SnackBean ls1=new SnackBean();
ls1.id="124";
ls1.name="薯片";
ls1.price="5";
SnackBean ls2=new SnackBean();
ls2.id="124";
ls2.name="薯愿";
ls2.price="8";
set11.add(ls);
set11.add(ls1);
set11.add(ls2);
// for (SnackBean sk:set11
// ) {
// System.out.println(sk.id+" "+sk.name+" "+sk.price);
// }
for (Iterator<SnackBean> iterator = set11.iterator(); iterator.hasNext(); ) {
SnackBean next = iterator.next();
System.out.println(next.id+" "+next.name+" "+next.price);
}
}
}

上一篇:【JAVA基础】18 集合2


下一篇:TreeMap