Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Specify Map in Java generics

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

@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!

>Solution :

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>>>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading