Why I'm not getting a class cast exception or some thing else when adding element to TreeSet

Viewed 594

The below is my code

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.

3 Answers
Related