Search code examples
javacollectionswrappercomparable

Why object of number can be added in TreeSet


The object of class which we want to add into TreeSet, that Class must implement Comparable interface But Number class does not implement Comparable then how TreeSet allow Number to get added.

    Number n1= 11;
    Number n2= 12;
    Number n3= 13;
    Set<Number> set = new TreeSet<>();
    set.add(n1);
    set.add(n2);
    set.add(n3);

Solution

  • You are right

    Class must implement Comparable interface.

    And here in your example the above statement is valid. Number has child class Integer and when we do this:

     Number n1= 11;
    

    On runtime it create Integer object and Integer implement the Comparable.

    You can also see this in java doc. here

    OR We can also proof with program like this:

    Number n1 = 10;
    System.out.println(n1 instanceof Number);   //true  
    System.out.println(n1 instanceof Integer);  //true  
    System.out.println(n1 instanceof Comparable);   //true  
    

    Hope this help!