问题描述
我想使用 Properties
类填充 HashMap
.
我想加载 .propeties
文件中的条目,然后将其复制到 HashMap
.
I want to populate a HashMap
using the Properties
class.
I want to load the entries in the .propeties
file and then copy it into the HashMap
.
之前,我只是用属性文件初始化HashMap
,但现在我已经定义了HashMap
,只想在构造函数中初始化它.
Earlier, I used to just initialize the HashMap
with the properties file, but now I have already defined the HashMap
and want to initialize it in the constructor only.
较早的方法:
Properties properties = new Properties();
try {
properties.load(ClassName.class.getResourceAsStream("resume.properties"));
} catch (Exception e) {
}
HashMap<String, String> mymap= new HashMap<String, String>((Map) properties);
但现在,我有这个
public class ClassName {
HashMap<String,Integer> mymap = new HashMap<String, Integer>();
public ClassName(){
Properties properties = new Properties();
try {
properties.load(ClassName.class.getResourceAsStream("resume.properties"));
} catch (Exception e) {
}
mymap = properties;
//The above line gives error
}
}
如何在此处将属性对象分配给 HashMap
?
How do I assign the properties object to a HashMap
here?
推荐答案
如果我理解正确的话,属性中的每个值都是一个代表整数的字符串.所以代码看起来像这样:
If I understand correctly, each value in the properties is a String which represents an Integer. So the code would look like this:
for (String key : properties.stringPropertyNames()) {
String value = properties.getProperty(key);
mymap.put(key, Integer.valueOf(value));
}
这篇关于使用属性文件中的条目填充 HashMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!