Nilendu Kumar
Nilendu Kumar

Reputation: 73

Why is this code snippet giving an error?

    Set set=new TreeSet();

    set.add(2);
    set.add(1);
    set.add("3");
    System.out.println(set);

Set is a Collection and it is not homogeneous so it should take any value (Both Integer and String)

Upvotes: 2

Views: 357

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500375

TreeSet stores its values in order - which means they have to be comparable with each other. You can't compare an Integer with a String, so you get an exception at execution time.

If you really want to be able to do this, you could provide your own custom Comparator to the constructor of the TreeSet, implementing what ever comparison logic you want.

Upvotes: 5

Related Questions