【发布时间】:2015-08-27 00:35:40
【问题描述】:
我在 Java 类中多次遇到这种模式:
public class MyClass {
private static final String firstAttributeKey = "FirstAttribute";
private static final String secondAttributeKey = "SecondAttribute";
...
private String firstAttributeValue = null;
private String secondAttributeValue = null;
...
public void setProperty(String key, String value) {
if(key.equals(firstAttributeKey) {
firstAttributeValue = value;
} else if(key.equals(secondAttributeKey) {
secondAttributeValue = value;
...
}
public void getProperty(String key, String value) {
if(key.equals(firstAttributeKey) {
return firstAttributeValue;
} else if(key.equals(secondAttributeKey) {
return secondAttributeValue;
...
}
...
}
此模式包含一长串键值对。我想知道这种结构的优点是什么。在我看来,简单地创建一个哈希图来存储键值对似乎更容易、更有效。
【问题讨论】:
-
所以你只存储两个值,不是吗?并且键始终应该是 FirstAttribute 和 SecondAttribute 以在您的结构中存储值
-
...这只是一个sn-p。可能有 40-50 个属性,所有属性都有一个键和值声明,以及一个 set 和 get 语句。我不明白你为什么想要这样的实现
-
也许这段代码的作者根本不了解地图并试图重新发明轮子?或者它是一些(可能是被误导的)优化性能的尝试。
-
在我看来,使用这种方法而不是 HashMap 简直是疯了。我看到这可能提供的唯一好处是控制允许的键 - 但即使使用 HashMap 也有更好的方法来实现这一点。 (我假设
voidgetter 是一个错字。)