Home > Blockchain >  Java Generics - relationship between two type parameters
Java Generics - relationship between two type parameters

Time:07-06

Fairly embarrassed to ask this is likely to turn out to be simple, but seemingly cannot find an answer.

I have an interface Cacheable

/**
    K denotes the type of the key of a cacheable object
*/
public interface Cacheable<K extends Serializable> extends Serializable{
   K getKey();
}

Then I have a cache that stores the cacheables

/**
 Cache that can store an object of type T and it's key which is of type K
*/

public interface Cache<K, T extends Cacheable>{
   Optional<T> get(K key);
   T put(T cacheable);
}

While this would work, I would like this to be better as the above doesn't express a relationship between T and K. In other words the fact that T.getKey should return a K is not being enforced here.

Something along the lines of the below is what I was looking for, but obviously it's not compileable. Thoughts on how I can do it?

public interface Cache<K, T<K> extends Cacheable<K>>

CodePudding user response:

You can't have higher-order generics in Java (which is why your T<K> trick doesn't compile), but you can have generics that are bounded by other generics. I believe you're looking for

public interface Cache<K, T extends Cacheable<K>>
  • Related