1

Can someone please explain me this class definition statement

public class BinarTree<Type extends Comparable<Type>> {...

I completely understand the purpose of it but not the syntax. According to me it should be just

public class BinarTree<Type extends Comparable> {...

What's the meaning of

<Type extends Comparable<Type>> ?
                         ^^^^
1
  • 1
    comparable is also a generic class(interface), and you want to use it in the generic way not in the raw way Commented Nov 20, 2014 at 7:48

3 Answers 3

5

Comparable is a generic interface. The reason behind that is to avoid casting to a specific type in the Comparable#compareTo(...) method.

So if a Type extends Comparable<Type> this would mean that the Type will derive a method with signature

public int compareTo(Type t1)

instead of

public int compareTo(Object o1)

Sign up to request clarification or add additional context in comments.

Comments

1

The interface Comparable is itself a template. So what you have there is a template with a parameter that must extend a template. And specifically it must extend a template that received the extending class as a parameter.

Comparable is a template for interfaces that implement an order relationship and implement the method int compareTo(TYPE o). So it's normal to define a class:

  class FooBar implements Comparable<FooBar> {...

A binary tree wouldn't work for a class that was declared:

  class FooBar implements Comparable<Snafu> {...

That's because you would be able to compare FooBars to Snafus but not each other.

Comments

0

In

public class BinarTree<Type extends Comparable>{...

Type can be any Comparable, also Comparable<Integer> or Comparable<OtherType>. If this is what you want, it is fine. Most times, I think you know what you want to compare exactly, so specialize the Comparable to Comparable<Type>

1 Comment

I would at least use Comparable<?> and not the raw type Comparable if that is what I wanted. Avoid using raw types - they only exist for backward compatibility with old Java versions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.