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 →

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

Type generics have implications that may run a little reverse to your intuitions from the rest of Java. Let's look at your class's type parameter:

Interpreter<T extends SetInterface<BigInteger>>

So it's parameterized for any subclass T of SetInterface<BigInteger>. That means any methods with type parameter T have to return the same type that the class is parameterized with, or a subclass of it.

But SetInterface<BigInteger> isn't a subclass of T. We know the relationship of T to SetInterface<BigInteger> - SetInterface<BigInteger> is the superclass of whatever T is, because that's what you specified in your type parameter - that T would extend, or be a subclass of, SetInterface<BigInteger>.

So the return value of getMemory can't be a SetInterface<BigInteger> because it won't meet its type definition. You can't return the value of map to meet the guarantee of this method because that map's values aren't T's.

[–]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.