保存唯一的枚举对并将值与它们关联
我有 2 个枚举,并且存在每个枚举值与其他枚举值的组合。例如,我有 2 个枚举,每个枚举有 5 个可能的值,即 25 种可能的组合。我想要一种方法让类的对象实例为每个组合“拥有”一个值。
我有点不知道该怎么做。我认为这是一个类设计问题,我忘记了一些明显的事情。到目前为止,我想到的是使用 Java 中的 Map 来保存基本上一对。该类有一个枚举 A 的值和一个枚举 B 的值,它的相等比较比较两个枚举的值是否相同相同的。 所以(在代码中):
class EnumPair {
EnumA a;
EnumB b;
}
// with equals() implemented
然后我使用一个映射,该映射将对类作为键,然后将值作为键的值。这允许我将值有效负载与对相关联。但我不确定我所做的是否正确?我所拥有的是:
class EnumPair {
EnumA a;
EnumB b;
}
class ValueHolder {
int someInt;
String someText;
}
Map<EnumPair, ValueHolder> = new HashMap<>();
地图是正确的方法吗?因为 EnumPair 可能的组合数量也有限,因为它是一个枚举和另一个枚举的组合。由于枚举的定义有限,因此可能的组合数量有限。在本例中,将有 25 种组合。这意味着,当技术上只存在 25 种可能的组合,并且每个包含这些组合的映射实例的值不同时,为每个映射生成最多 25 个包含一对枚举的对象有点浪费。
我不知道如果没有地图我该如何建模。我认为地图的方向可能是正确的,但是有限的现有对可以存在于代码中吗?我觉得我错过了一些关键的理论,或者忘记了一些设计类或数据类型的方法,因为我对如何做到这一点感到困惑。我觉得泛型可能属于解决方案的范畴,但我就是无法理解它。
I have 2 enums, and a combination of each enum value with each other enum value exists. So for example with my 2 enums of 5 possible values each, that is 25 possible combinations. I want a way for an object instance of a class to "have" a value for each combination.
I am a little bit stumped on how to do it. I think it's a class design problem and I'm forgetting something obvious. So far what I thought of is to use a Map in Java that holds basically a pair.. The class has a value for an enum A and a value for an enum B, and its equality comparison compares whether the value for both enums are the same.
So (in code):
class EnumPair {
EnumA a;
EnumB b;
}
// with equals() implemented
Then I use a map that holds the pair class as a key and then a value as a value for the key.. This allows me to associate value payloads to the pairs. But I'm not sure if what I'm doing is correct? What I have is:
class EnumPair {
EnumA a;
EnumB b;
}
class ValueHolder {
int someInt;
String someText;
}
Map<EnumPair, ValueHolder> = new HashMap<>();
Is the map the right way to go about it? Because there are also a limited amount of combinations possible for the EnumPair since it is a combination of one enum and another enum. Because enums have finite definitions, there are a limited amount of combinations possible. In this instance it would be 25 combinations. This would mean that it's sort of a waste to generate up to 25 objects containing a pair of enums per map for the pairs when technically only 25 possible combinations exist, and only the values differ per instance of a map holding these combinations.
I don't know how I would model this without the map though. I think the map might be in the right direction, but where could limited existing pairs live in the code? I feel like I am missing some key piece of theory or forgetting some way to design classes or data types, because I am puzzled on how to do this. I feel like generics might be in the realm of the solution but I just can't wrap my head around it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论