简体   繁体   中英

How to add two enums to a single Map object as key and value

I have two enums. I would like to create a Map object out of the two enums.

I have gone through EnumMap but it says only the key can be an enum. Please correct me if i am wrong.

private enum Export {
    BINGOEXPORT, DEFECTSEXPORT, IBC3EXPORT, IBCONTRACTSEXPORT, 
    RMAHEADEREXPORT, RMALINESEXPORT, SITESEXPORT, SREXPORT
};

private enum Preperation {
    BINGOPREPERATION, DEFECTSPREPERATION, IBC3PREPERATION, 
    IBCONTRACTSPREPERATION, RMAHEADERPREPERATION, RMALINESPREPERATION, 
    SITESPREPERATION, SRPREPERATION, IBEXPORTLOGPREPERATION
};

A normal HashMap works fine to have the enum as a key and value.

Map<Export, Preparation> myMap = new HashMap<>();
myMap.put(Export.BINGOEXPORT, Preparation.BINGOPREPERATION);

If you would like to use one enum as the key and the other one as a value, EnumMap allows you to do that ( demo ):

EnumMap<Export,Preparation> e2p = new EnumMap<Export,Preparation>(Export.class);
e2p.put(Export.RMALINESEXPORT, Preparation.SRPREPERATION);
System.out.println(e2p.get(Export.RMALINESEXPORT));

If you would like to mix enum s as keys of the same Map , one approach is to make a common interface for the two enum s, and use it as the key type for your Map . You can do it because Java enum s are allowed to extend classes and implement interfaces:

private interface CommonKey {
    int hashCode();
    boolean equals(Object other);
}

private enum Export implements CommonKey {
    BINGOEXPORT, DEFECTSEXPORT, IBC3EXPORT, IBCONTRACTSEXPORT, RMAHEADEREXPORT, RMALINESEXPORT, SITESEXPORT, SREXPORT
}

private enum Preperation implements CommonKey {
    BINGOPREPERATION, DEFECTSPREPERATION, IBC3PREPERATION, IBCONTRACTSPREPERATION, RMAHEADERPREPERATION, RMALINESPREPERATION, SITESPREPERATION, SRPREPERATION, IBEXPORTLOGPREPERATION
}

Now you can declare your map:

Map<CommonKey,SomeClass> myMap = new HashMap<>();
myMap.put(Export.BINGOEXPORT, someObject);
myMap.put(Preperation.RMAHEADERPREPERATION, antherObject);

Both interface methods are optional, because they are inherited from java.lang.Object . I added them to the interface anyway, to make it easier for your readers to understand what parts of the implementing classes are important for your use of the interface.

您可以尝试制作两个实现相同接口的枚举

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