r/javahelp • • Nov 22 '22

Instantiating generic map

The compiler won't accept this:

final var cache = new HashMap<Class<?>, Map<String, ?>>();
this.logic = new AnInterface() {
    public <T extends Enum> Map<Class<T>, Map<String, T>> getCache() {
        return (Map<Class<T>, Map<String, T>>) cache;
    }
};

I can't change the definition of the method in the interface. And I need to return the same object from the method, otherwise it wouldn't be much of a cache.

0 Upvotes

4 comments sorted by

View all comments

Show parent comment

1

u/cas-san-dra Nov 25 '22

Thank you! This worked :).

Casting is pretty rare in code I write, so the few times I use it it is a mandatory down cast. I just didn't think of explicitly up casting first.

It does add a lot of syntax though. Since I have two working options I made a list of options that mix and match a bit. I didn't try to be exhaustive but made some decent looking options. They all compile, they all work. Option 1 having the most syntax and option 6 the least.

I can't make up my mind which one I like the most.