我正在尝试实现一个解决方案(在 Java 1.6 中),我需要存储一些值(用于一组属性)并考虑以下三个选项的三个选项(当然欢迎任何其他想法!)
选项 1
创建一个类(称之为 Property
),它可以存储不同类型的对象(字符串、整数、 boolean 值...),并将属性集作为 List<Property>
使用。
类似于:
private String type; //Store the type of Object
private String name; //Store the name of the property
private String valueStr; //Store the String value
private int valueInt; //Store the int value
private boolean valueBool; //Store the boolean value
我真的不喜欢拥有许多属性并只使用其中一个的想法。 (每个属性只会设置一个值)
选项 2
使用 HashMap<String, Object>
并解析每个案例的类型。
有好东西你可以得到Property
按名字
选项 3
使用 HashMap<String, Property>
其中String为属性名,通过名称即可获取值,无需解析。
问题是: 你认为哪一个是最好的? 或者如果他们都不好,我想听听其他想法
还有List和HashMap在性能上有什么区别吗?
在此先感谢您的帮助。
最佳答案
我认为最好有一个像这样的自定义值类:
public class MyValue {
enum Type {
INT, STRING, BOOL;
}
private Type type; //Store the type of Object in Type Enum
private Object value; //Store the value in Object
public void setValue(int val) {
type = Type.INT;
value = new Integer(val);
}
public void setValue(String val) {
type = Type.STRING;
value = val;
}
public void setValue(boolean val) {
type = Type.BOOL;
value = new Boolean(val);
}
public String stringVal() {
// check type to be STRING first
return (String) value;
}
public int intVal() {
// check type to be INT first
return ((Integer) value.intValue());
}
public boolean booleanVal() {
// check type to be BOOL first
return ((Boolean) value.booleanValue());
}
}
您需要根据 getter 中的 enum Type
从 Object 转换为特定类型。
关于java - List<CustomObject> 和 HashMap <String, Object> 之间有什么优势吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16219936/