TreeSet和TreeMap排序集合,排序的实现

/**
 * TreeMap不能直接增强for循环
 * TreeSet和TreeMap不同于其他的集合的特殊的特点是插入的元素类型需要指定比较规则
 */
public class TreeMapTest {
    public static void main(String[] args){

        TreeMap<Animal,Integer> treeMap =new TreeMap<>(new Comparator<Animal>() {
            @Override
            public int compare(Animal o1, Animal o2) {
                return o1.age-o2.age;
            }
        });

        treeMap.put(new Animal(20),10);
        treeMap.put(new Animal(3000),10);
        treeMap.put(new Animal(500),10);

        Set<Map.Entry<Animal, Integer>> entrySet = treeMap.entrySet();
        for (Map.Entry<Animal, Integer> animalIntegerEntry : entrySet) {
            System.out.println(animalIntegerEntry);
        }
        TreeMap<String,String > treeMap1=new TreeMap<>();
        treeMap1.put("sadf", "asfd");
        // treeMap1.for   TreeMap 类型的不能直接增强for循环
        //
        //
        TreeSet<Animal> treeSet =new TreeSet<>(new Comparator<Animal>() {
            @Override
            public int compare(Animal o1, Animal o2) {
                return o1.age-o2.age;
            }
        });
        treeSet.add(new Animal(20));
        treeSet.add(new Animal(230));
        treeSet.add(new Animal(201));










    }
}

//--------------------------------
class  TreeMapTestComparator /*implements Comparator<Animal>*/ {
   /* @Override
    public int compare(Animal o1, Animal o2) {
        return o1.age-o2.age;
    }*/
}
class Animal{
    int age;

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Animal)) return false;
        Animal animal = (Animal) o;
        return age == animal.age;
    }

    @Override
    public int hashCode() {

        return Objects.hash(age);
    }

    public Animal() {

    }

    public Animal(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Animal{" +
                "age=" + age +
                '}';
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值