How can i do this ? When i stored my fields in HashMap , i did it like simple Objects
HashMap map = new HashMap();
map.put ("Autorul",numelePrenumeleAutorului);
map.put ("Denumirea cartii",denumireaCartii);
map.put ("Culoarea cartii",culoareaCartii);
map.put ("Genul cartii",gen);
m开发者_如何学Pythonap.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);
I access values from HashMap (look for the last lines)
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);
}
}
Object[] array = ((ArrayList) map.get(key)).toArray();
First of: you're in object denial. Your HashMap
should really be a proper class that you wrote with the real properties to hold your different fields.
That way you also don't have to do that ugly "name of the property"-to-local-variable mapping.
Next: if what you put into the map is an ArrayList
, then you can just cast what you get out to that type again:
ArrayList temp = (ArrayList) map.get(key);
精彩评论