在 HashMap 中存储数组

2022-09-01 11:17:11

我是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");     
    }   
}

答案 1
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);

答案 2

不确定确切的问题,但这是你要找的吗?

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});
     }
}