我是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");
}
}
Run Code Online (Sandbox Code Playgroud)
jef*_*eff 30
不确定确切的问题,但这是你在寻找什么?
public class TestRun
{
public static void main(String [] args)
{
Map<String, Integer[]> prices = new HashMap<String, Integer[]>();
prices.put("milk", new Integer[] {1, 3, 2});
prices.put("eggs", new Integer[] {1, 1, 2});
}
}
Run Code Online (Sandbox Code Playgroud)
jor*_*b87 27
HashMap<String, List<Integer>> map = new HashMap<String, List<Integer>>();
HashMap<String, int[]> map = new HashMap<String, int[]>();
Run Code Online (Sandbox Code Playgroud)
例如,选择一个
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]);
}
Run Code Online (Sandbox Code Playgroud)
要不就
HashMap<String, int[]> map = new HashMap<String, int[]>();
map.put("Something", coeficientUzura);
Run Code Online (Sandbox Code Playgroud)
是的,Map接口允许您将Arrays存储为值.这是一个非常简单的例子:
int[] val = {1, 2, 3};
Map<String, int[]> map = new HashMap<String, int[]>();
map.put("KEY1", val);
Run Code Online (Sandbox Code Playgroud)
此外,根据您的使用情况,您可能希望查看番石榴提供的Multimap支持.
| 归档时间: |
|
| 查看次数: |
112020 次 |
| 最近记录: |