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)

Jon Skeet
people
quotationmark

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.

people

See more on this question at Stackoverflow