java - 如何使用通用 Treeset 创建比较器?

标签 java generics treeset

需要泛型方面的帮助,我有这个类:

public class Course<T> {

    private T idOrName;
    private float avg;

    public Course(T idOrName,float avg){
        this.idOrName=idOrName;
        this.avg=avg;

    }


}

....我需要让用户在字符串或整数之间进行选择,然后创建一个树集并按此泛型类型对其进行排序。如果我不知道它是数字还是字符串,我该怎么做?我在制作比较器时遇到问题:

    Set<Course<?>> list=new TreeSet<>(new Comparator<Course<?>(){

        @Override
        public int compare(Course<?> o1, Course<?> o2) {
            // TODO Auto-generated method stub
            return 0;
        }

    });

最佳答案

首先,您需要通过继续下一步来表明预期的类必须是Comparable

public class Course<T extends Comparable<T>> {
   ...
}

那么你的通用比较器可能是这样的:

Set<Course<?>> list = new TreeSet<>(new Comparator<Course<?>>(){

    @Override
    public int compare(Course<?> o1, Course<?> o2) {
        // If idOrName are both of the same class then we use the
        // comparator of this class as we know that they are Comparable
        if (o1.idOrName.getClass() == o2.idOrName.getClass()) {
            return ((Comparable)o1.idOrName).compareTo((Comparable)o2.idOrName);
        }
        // If they are not of the same class we compare the name of the class
        return o1.idOrName.getClass().getName().compareTo(
            o2.idOrName.getClass().getName()
        );
    }
});

关于java - 如何使用通用 Treeset 创建比较器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39118973/

相关文章:

java - 如何在 Java 中使用 SQL Server 日期时间类型

java - BigInteger 乘法中的前导零

c# - 你能给我一个 LINQ/lambda 代码练习的资源吗?

Java TreeSet 的 contains 实现(源代码)缺失

java - Hibernate 查询在论坛问题中搜索内容

Java泛型——删除概念

c# - 通用类型函数 : return a non-nullable value

java - 在某些情况下,TreeSet Comparator 无法删除重复项?

java - 具有泛型类型的 Map.Entry 的树集实现

java - 安卓 : Adding tabs below the action bar