• Post Reply Bookmark Topic Watch Topic
  • New Topic

Flexible Comparisons with Wildcards  RSS feed

 
Shay Levy
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

I was looking at a snippet of code that was part of an example for flexible comparisons with wildcard and there was something that I didnt understand.
First here is the the code (I changed it a little bit because the names were longer in the book)



The following method suppose to determain who is stronger:



I understand that line (1) cannot compile because dog is not Comparable<Dog> but Comparable<Animal>.
I also understand that line (2) can work because the type parameter that is passed (Animal) satisfies the method signiture.
what I dont understand is why line (3) is working, what is the compiler checking that enables line (3) but not (1)? What is the Type (T) that is actually used when executing line (3)?

I hpoe my questions were clear.

Thanks

 
John de Michele
Rancher
Posts: 600
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Shay:

The reason why three works is because Animal, Cat, and Dog all implement Comparable<Animal>. Since you are assigning the return reference to a reference of type Animal, it works.

John.
 
Shay Levy
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi John,



The above code generate compiler error:
incompatible types
found: stronger
required: [PackageName.Animal]

Animal and Dog implements Comparable<Animal>, So I dont understand why i get a compiler error

Thanks
 
John de Michele
Rancher
Posts: 600
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Shay:

So I tried your code myself, and I realized that I had made a mistake in my previous response to you. Dog and Cat do not implement Comparable<T>, they only extend a class that does (Animal). That's why your first line fails. You're comparing objects of type Dog to each other, not of type Animal (the JVM is not smart enough to know that you want to compare them on their Animal types). The second line works because you do a generic cast to Animal. The third line works because Cat and Dog share the Animal type. If you change your variable initializations to this, everything should work:

John.
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Change your method signature to this:
In normal words, accept anything that is comparable to instances of itself or one of its parent classes. This way, Dog is a valid substitute for T as it is comparable to its direct super class.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!