将数组存储在HashMap中 [英] Store an array in HashMap
本文介绍了将数组存储在HashMap中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是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);
尝试{
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(发生异常);
$ / code $ / pre
解决方案
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 map.get(Something)。add(coeficientUzura [i]);
或者只是
HashMap< String,int []> map = new HashMap< String,int []>();
map.put(Something,coeficientUzura);
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[]>();
pick one, for example
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]);
}
or just
HashMap<String, int[]> map = new HashMap<String, int[]>();
map.put("Something", coeficientUzura);
这篇关于将数组存储在HashMap中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文