Help matching fields between two classes

前端 未结 2 1798
一整个雨季
一整个雨季 2021-01-27 04:20

I\'m not too experienced with Java yet, and I\'m hoping someone can steer me in the right direction because right now I feel like I\'m just beating my head against a wall...

相关标签:
2条回答
  • 2021-01-27 04:56

    You're probably better off using a Map rather than a List, you can use the enum as the key and get the values out.

    Map<YourEnumType,ValueType> map = new HashMap<YourEnumType,ValueType>();
    
    0 讨论(0)
  • 2021-01-27 04:56

    @Tom's recommendation to use Map is the preferred approach. Here's a trivial example that constructs such a Map for use by a static lookup() method.

    private enum Season {
    
        WINTER, SPRING, SUMMER, FALL;
        private static Map<String, Season> map = new HashMap<String, Season>();
        static {
            for (Season s : Season.values()) {
                map.put(s.name(), s);
            }
        }
    
        public static Season lookup(String name) {
            return map.get(name);
        }
    }
    

    Note that every enum type has two implicitly declared static methods:

    public static E[] values();
    public static E valueOf(String name);
    

    The values() method returns an array that is handy for constructing the Map. Alternatively, the array may be searched directly. The methods are implicit; they will appear in the javadoc of your enum when it is generated.

    Addendum: As suggested by @Bert F, an EnumMap may be advantageous. See Effective Java Second Edition, Item 33: Use EnumMap instead of ordinal indexing, for a compelling example of using EnumMap to associate enums.

    0 讨论(0)
提交回复
热议问题