Skip to content
Advertisement

Java instance for comparable

Why is it legal to create new Box(); and new Box<Integer>();? Is it because Box is comparable?

JavaScript

Advertisement

Answer

You have declared the class with a generic type parameter. This is not the same as implementing the Comparable interface:

JavaScript

Is the same as:

JavaScript

Which is not the same as:

JavaScript

Because the type parameter is unbounded, it will accept any type. So you can use an Integer or a String:

JavaScript

The reason why you can create a new Box without specifying the type is because of backwards compatibility. The new Box would have the raw type Box<T>. It is bad practice and should be avoided.

You can read more about Raw Types here

If you wanted to enforce that the type parameter implements Comparable, then you can do:

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement