我是 Java 新手。如何将整数值数组存储在 HashMap 中,之后我将这个 HashMap 写入 txt 文件,但这目前并不重要。我可以存储单个字段,但不能存储数组。有任何想法吗 ?
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");
}
}
最佳答案
HashMap<String, List<Integer>> map = new HashMap<String, List<Integer>>();
HashMap<String, int[]> map = new HashMap<String, int[]>();
选择一个,例如
HashMap<String, List<Integer>> map = new HashMap<String, List<Integer>>();
map.put("Something", new ArrayList<Integer>());
for (int i=0;i<numarulDeCopii; i++) {
map.get("Something").add(coeficientUzura[i]);
}
或者只是
HashMap<String, int[]> map = new HashMap<String, int[]>();
map.put("Something", coeficientUzura);
关于java - 在 HashMap 中存储一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7602665/