【发布时间】:2012-02-13 11:50:18
【问题描述】:
我有一个奇怪的问题。也许我的做法是错误的,但让我们看看这个问题的去向:)
我想要一个包含字符串或字符串列表的地图容器。我想在构造这个对象的过程中强制执行这个规则,这样你就不能创建一个值不是其中任何一个的映射。
例如
class Record {
public Record(String key, Map<String,Object> attrs) {
// check that attrs only contains Objects which are Strings or List<Strings>
}
}
我想到的其他解决问题的方法可能是......
1)
class Record {
public Record(String key, Map<String,String> attrs, Map<String,List<String>> multiAttrs) {
// ...
}
}
2)
class Record {
public Record(String key, Map<String,Value> attrs) {
// ...
}
}
class Value {
// Create some funky class that encapsulates lists.
// Perhaps returning the only element in the list if the size is 1,
// but returning the list otherwise
}
我并没有立即对替代方案感到兴奋,但我只是把它作为我已经考虑过的东西放在那里。我真的希望 Strings 和 List 之间的区别对类的用户是透明的。
【问题讨论】:
-
第三个想法是我能想到的最好的了。我还会按照 epoch 的建议查看来自 Guava 库的多图。
标签: java