TreeSet集合:


返回值规则
package com.itheima.d1_set;import java.util.Comparator;import java.util.Set;import java.util.TreeSet;/*** 目标: 观察TreeSet 对于有值特性的数据如何排序* 学会对自定义类型的对象进行指定规则排序*/public class SetDemo4 {public static void main(String[] args) {// TreeSet 不重复,无索引 可排序TreeSet<Integer> sets = new TreeSet<>();sets.add(23);sets.add(24);sets.add(12);sets.add(8);System.out.println(sets);// TreeSet 不重复,无索引 可排序TreeSet<String> sets1 = new TreeSet<>();sets1.add("Java");sets1.add("Java");sets1.add("angela");sets1.add("黑马");sets1.add("Java");sets1.add("About");sets1.add("Python");sets1.add("UI");sets1.add("UI");// [About, Java, Python, UI, angela, 黑马]System.out.println(sets1); // TreeSet集合对于字符串是按照字母顺序排序的System.out.println("----------------------");// 方式二: 集合自带比较器对象进行规则定制 // 如果两种方式都有,默认用集合自带比较器对象的(方式二)Set<Apple> apples = new TreeSet<>(new Comparator<Apple>() {@Overridepublic int compare(Apple o1, Apple o2) {// return o1.getWeight() - o2.getWeight(); // 默认第一个减第二个参数就是升序// return o2.getWeight() - o1.getWeight(); 降序// 像这种比较价格的,要用Double.compare的方法比较,避免小数相减失真return Double.compare(o2.getPrice(), o1.getPrice()); //降序}});// 创建TreeSet集合(用多态的形式,用父类接口Set接收)// Set<Apple> apples = new TreeSet<>();apples.add(new Apple("红富士","红色",9.9,500));apples.add(new Apple("青苹果","绿色",15.9,300));apples.add(new Apple("绿苹果","青色",29.9,400));apples.add(new Apple("黄苹果","红色",9.8, 500)); // 去掉重量重复的元素System.out.println(apples); // 自定义比较规则后,按照重量排序// [Apple{name='青苹果', color='绿色', price=15.9, weight=300}, Apple{name='绿苹果', color='青色', price=29.9, weight=400}, Apple{name='红富士', color='红色', price=9.9, weight=500}]}}
package com.itheima.d1_set;// 使用Apple类 去实现接口的某种功能 // Comparable这里是比较功能的接口,传入Apple对象public class Apple implements Comparable<Apple>{private String name;private String color;private double price;private int weight;public Apple() {}public Apple(String name, String color, double price, int weight) {this.name = name;this.color = color;this.price = price;this.weight = weight;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getColor() {return color;}public void setColor(String color) {this.color = color;}public double getPrice() {return price;}public void setPrice(double price) {this.price = price;}public int getWeight() {return weight;}public void setWeight(int weight) {this.weight = weight;}// 写javabean现在一般会再加一个toString方法(重写),如果有引用类型可以直接打印其内容@Overridepublic String toString() {return "Apple{" +"name='" + name + '\'' +", color='" + color + '\'' +", price=" + price +", weight=" + weight +'}';}/*** 方式一: 类自定义比较规则* @param o the object to be compared.* @return*/@Overridepublic int compareTo(Apple o) {// 按照重量进行比较的// this代表你本身这个对象,o表示你放到参数里的对象 这里的this相当于o1 , o相当于o2// this是现在定义的这个类的学生对象,o是拿来比较输入的学生对象return this.weight - o.weight; // 升序排序// return this.weight - o.weight >= 0 ? 1 : -1; // 保留去重复的元素}}



