Forums Register Login

Flexible Comparisons with Wildcards

+Pie Number of slices to send: Send
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

+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
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
+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
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.
This tiny ad is guaranteed to be gluten free.
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 870 times.
Similar Threads
Generics and ? symbol
Sorting "mutually comparable" objects using Collections.sort()
Difference between Comparable and Comparator
compareTo()
How does Type Inference (type parameter resolution) work?
More...

All times above are in ranch (not your local) time.
The current ranch time is
Apr 15, 2024 22:51:57.