在 HashMap 中存储一个数组 [英] Store an array in HashMap
本文介绍了在 HashMap 中存储一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是 Java 新手.如何将整数值数组存储在 HashMap 中,之后我将这个 HashMap 写入 txt 文件,但这目前并不重要.我可以存储单个字段,但不能存储数组.有任何想法吗 ?
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");
}
}
推荐答案
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);
这篇关于在 HashMap 中存储一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文