我该怎么做? 当我在HashMap中存储我的字段时,我就像简单的对象
一样HashMap map = new HashMap();
map.put ("Autorul",numelePrenumeleAutorului);
map.put ("Denumirea cartii",denumireaCartii);
map.put ("Culoarea cartii",culoareaCartii);
map.put ("Genul cartii",gen);
map.put ("Limba",limba);
map.put ("Numarul de copii",numarulDeCopii);
map.put ("Numarul de pagini",numarulDePagini);
map.put ("Pretul cartii",pretulCartii);
ArrayList arl=new ArrayList();
for (int i = 0;i<numarulDeCopii;i++) {
arl.add(coeficientUzura[i]);
}
map.put ("Coeficientii de Uzura",arl);
我从HashMap访问值(查找最后一行)
Carte (String caleSpreFisier) {
HashMap map = new HashMap();
File file = new File(caleSpreFisier);
try {
FileInputStream f = new FileInputStream(file);
ObjectInputStream s = new ObjectInputStream(f);
map = (HashMap)s.readObject();
s.close();
} catch(Exception e){
System.out.println("An exception has occured : "+e);
}
for (Object key :map.keySet()) {
if (key.equals("Autorul")) {
numelePrenumeleAutorului = (String)map.get(key);
}
if (key.equals("Denumirea cartii")) {
denumireaCartii = (String) map.get(key);
}
if (key.equals("Culoarea cartii")) {
culoareaCartii = (String)map.get(key);
}
if (key.equals("Genul cartii")) {
gen = (String) map.get(key);
}
if (key.equals("Limba")) {
limba = (String) map.get(key);
}
if (key.equals("Numarul de copii")) {
numarulDeCopii = (Integer) map.get(key);
}
if (key.equals("Numarul de pagini")) {
numarulDePagini = (Integer) map.get(key);
}
if (key.equals("Pretul cartii")) {
pretulCartii = (Double) map.get(key);
}
if (key.equals("Coeficientii de Uzura")) {
ArrayList temp = new ArrayList();
Object me = map.get(key);
System.out.println(me);
//temp = (ArrayList) map.get(key);
}
}
答案 0 :(得分:0)
Object[] array = ((ArrayList) map.get(key)).toArray();
答案 1 :(得分:0)
首先:你在object denial。你的HashMap
应该是一个合适的类,你用真实的属性写下来保存你的不同领域。
这样你也不必做那个丑陋的“属性名称”-to-local-variable映射。
下一步:如果你放入地图的内容是ArrayList
,那么你可以再次将你得到的内容转换为该类型:
ArrayList temp = (ArrayList) map.get(key);