i'm new to Java. How can i store an array of integers values in a HashMap, after that i write this HashMap in a txt file but this isn't important at the moment. I can store single fields but not an array. Any ideas ?
public void salveazaObiectulCreat(String caleSpreFisier) {
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);
try {
File file = new File(caleSpreFisier);
FileOutputStream f = new FileOutputStream(file);
ObjectOutputStream s = new ObjectOutputStream(f);
s.writeObject(map);
s.close();
} catch(Exception e){
System.out.println("An exception has occured");
}
}
Your life will be much easier if you can save a List as the value instead of an array in that Map.
You can store objects in a HashMap.
HashMap<String, Object> map = new HashMap<String, Object>();
You'll just need to cast it back out correctly.
pick one, for example
or just
Not sure of the exact question but is this what you are looking for?
Yes, the Map interface will allow you to store Arrays as values. Here's a very simple example:
Also, depending on your use case you may want to look at the Multimap support offered by guava.
If you want to store multiple values for a key (if I understand you correctly), you could try a MultiHashMap (available in various libraries, not only commons-collections).