为什么我在TreeSet中添加元素时没有得到类转换异常或者其他的东西 [英] Why I'm not getting a class cast exception or some thing else when adding element to TreeSet

查看:112
本文介绍了为什么我在TreeSet中添加元素时没有得到类转换异常或者其他的东西的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我的代码

class NumberComparator<Number> implements Comparator<Number> {
    public int compare(Number o1, Number o2) {
        return 1;
    }
}

public class Ex28 {
    public static void main(String[] args) {
        TreeSet set = new TreeSet(new NumberComparator<Number>());
        set.add(1);
        set.add(1.4f);
        set.add(1L);
        set.add("1a");
        System.out.println(set);
    }
}

但仍然是当我添加任何东西,是一个字符串到它,它不给我任何异常。它只是工作正常。
我得到的输出为

As I have defined my own comparator of type Number , but still when I'm adding any thing else that is a string to it, it's not giving me any exception. It's simply working fine. I'm getting the output as

[1, 1.4, 1, 1a]

任何人都可以解释为什么会发生。

Can any one please explain why it's happening.

推荐答案

问题是一些不良做法的混合:

The problem is a mixture of some poor practices:


  • 您使用的原始类型 TreeSet

  • 您的 NumberComparator 是通用( Number 是一个类型参数)

  • You're using the raw type for TreeSet
  • Your NumberComparator is generic (Number is a type parameter)

Number 这里的类型参数意味着类型擦除意味着你不会实际转换为真实的 Number 类型。

The fact that Number is a type parameter here means that type erasure means you won't actually be casting to the real Number type.

如果您将比较器更改为:

If you change your comparator to:

class NumberComparator implements Comparator<Number> {
    public int compare(Number o1, Number o2) {
        return 1;
    }
}

和您的呼叫代码:

TreeSet set = new TreeSet(new NumberComparator());

然后我会预期会有例外。

then I'd expect an exception.

此外,如果您将代码更改为不使用原始类型:

Further, if you change your code to not use the raw type:

TreeSet<Number> set = new TreeSet<Number>(new NumberComparator());

那么你会得到一个编译时错误。

then you'll get a compile-time error instead.

这篇关于为什么我在TreeSet中添加元素时没有得到类转换异常或者其他的东西的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆