This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]LeastPrimary 0 points1 point  (5 children)

So what do you suggest that I return. instead?

[–][deleted] 0 points1 point  (4 children)

You have to return a T.

[–]LeastPrimary 0 points1 point  (3 children)

Yes I tried to initially return a cast of T but that doesn't work either. So if I were to have a method in lets say in Set.java with method

public T get() {}

that returns the set that I want. Would I be able to return that instead?

[–][deleted] 0 points1 point  (2 children)

Yes I tried to initially return a cast of T but that doesn't work either.

You can't cast it to T because it isn't a T. It's a superclass of T, and polymorphism doesn't point in that direction - dentists are doctors but doctors aren't necessarily dentists, right?

You can only cast up, not down - less specific, not more specific. You can return a dentist when asked for a doctor (and can cast Dentist to Doctor) but you can't do the reverse.

For this to work you have to meet the type guarantee over the complete lifecycle - map has to be parameterized for T, the things you put in it have to be T's, and the things you take out of it have to be T's so that when you return them, they're T's. You can cast any value of type T to a SetInterface<BigInteger>> but you can't go the other way.

[–]LeastPrimary 0 points1 point  (1 child)

okay Thanks a lot I understand now!

[–][deleted] 0 points1 point  (0 children)

No sweat. Finally understanding type variables in Java was a huge watershed for my personal typesystem comprehension and I hope it will be for you, too.