黑马程序员_日记54_TreeSet使用比较器和泛型的初级结合

来源:互联网 发布:mac dock栏动态效果 编辑:程序博客网 时间:2024/05/22 00:35

 ——- android培训、java培训、期待与您交流! ———-

查阅API,得到:
“TreeSet(Comparator

六、比较器的泛型定义方式分析

import java.util.*;class GenericDemo6{    public static void main(String[] args)    {        //方式二和方式一选其一,打开对于的代码块就可以了        TreeSet<Student> al1 = new TreeSet<Student>();//方式一让学生自身具备比较性        //TreeSet<Student> al1 = new TreeSet<Student>(new Comp());//方式二,让集合具备比较性        al1.add(new Student("Student--abc--1"));        al1.add(new Student("Student--abc--3"));        al1.add(new Student("Student--abc--2"));    }}class Person{    private String name;    Person(String name)    {        this.name = name;    }    public String getName()    {        return name;    }}/*<? super Student>所以<>可以填<Student>或者<Person>,注意<? super Student>的Student是跟着TreeSet<Student>中的Student走的!*///这个是让学生自身具备比较性class Student extends Person implements Comparable<Person>{    Student(String name)    {        super(name);    }    public int compareTo(Person s)    {        //Person s = new Student();这个是可以接受进来的,所以能比较        return this.getName().compareTo(s.getName());    }}/*<? super Student>所以<>可以填<Student>或者<Person>,注意<? super Student>的Student是跟着TreeSet<Student>中的Student走的!*//*//这是让集合具备比较性class Comp implements Comparator<Person>{    public int compare(Person s1,Person s2)    {        //Person s1 = new Student("abc1");所以是可以接受Student和Student的父类        return s1.getName().compareTo(s2.getName());    }}*/
0 0
原创粉丝点击