简体   繁体   中英

How to write a function in Java generalized to take in a map parameter that has different key types?

I have two enums:

enum Country { US, etc }
enum Language { EN, etc }

I want to be able to write a function that takes in a map that has either enum as the key:

checkMap(new HashMap<Language, Long>());
checkMap(new HashMap<Country, Long>());

The only ways I have figured out how to do it are the following:

1. private void checkMap(Map<? extends Enum, Long> mapParam) {...}

2. private <T> void checkMap(Map<T, Long> mapParam) {...}

3. private void checkMap(Map mapParam) {...}

None of these are super specific on the parameters I let in. (1) does the best by making it some subclass of Enum, but complicates much of the logic (which I am greatly simplifying here). (3) I have to do a ton of downstream casting, and I feel it's just generally bad practice.

I feel like I am missing something fairly obvious here.

I also know that I can write two separate method declarations with the different parameters, but there is so much repeat logic and I want to abstract that logic into a function and avoid duplicate code.

I use your option 2: use a generic type parameter T . In your example the methods are private so you have complete control over which methods can delegate to checkMap , and so do not need to be so concerned about delegations using inappropriate key types.

You can use an interface - make Country and Language implement some made-up interface and use it in method declaration:

interface Dummy{}
enum Country implements Dummy {...}
enum Language implements Dummy {...}

private checkMap(Map<Dummy, Long> map) {...}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM