java - 在 HashMap 中存储一个数组

标签 java 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);

  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/

相关文章:

java - 具有相同值的字符串文字不会在 Controller 中保留同步锁

java - Java 会按照我想要的方式解释这个 boolean 表达式吗?

java - 如何知道/获取hashmap的容量?

java - 使用 Streams 将字符串列表映射到 HashMap

java - 声明HashMap中 vector 的大小

java - 如何获取HashMap中某个key出现的次数?

java - url openstream 中的连接过多

java - 将文件夹中的所有文本文件组合成一个文件

java - JUnit 测试 - 对模拟对象进行 Assets 或验证(或两者)?

jsp - 在struts 2中迭代hashmap并根据其值检查或取消选中复选框