Home > OS >  Specify Map in Java generics
Specify Map in Java generics

Time:12-09

I have the following interface:

public interface IGenericCache<K, V> {

    void put(K key, V value);

    V get(K key);

}

Then I want to create a concrete class that takes CacheKey object as input and Map<String, List<String>> object as output. A conceptual example is as follows:

public class LocalCache<CacheKey, Map<String, List<String>>> implements IGenericCache<CacheKey, Map<String, List<String>>> {

    @Override
    public void put(CacheKey key, Map<String, List<String>> value) {
        // TODO
    }

    @Override
    public Map<String, List<String>> get(CacheKey key) {
        return null;
    }
}

Where CacheKey is like:

@Data // lombok annotation
public class CacheKey {
    private final String attr1;
    private final String attr2;
}

I have seen red wavy lines from IDE by using the implementation in the example above. But I couldn't fin the correct format to match the generics <K, V> in the interface.

Could anyone good at Java please correct me? Thank you in advance!

CodePudding user response:

By putting <> after the name of the class that you're defining, you're declaring tokens to be used as generics. But you don't want that, you just want to fill existing generic type arguments.

So just omit the first pair of <>:

public class LocalCache implements IGenericCache<CacheKey, Map<String, List<String>>>
  • Related