【问题标题】:Store an array in HashMap在 HashMap 中存储一个数组
【发布时间】:2011-09-29 19:53:38
【问题描述】:

我是 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 中?
  • 数组和任何其他对象应该没有区别。你尝试了什么?
  • map.put 中的那些值是字符串,现在我想存储一个 int 值数组(一些数字)
  • 我们需要查看其余代码,例如numelePrenumeleAutorului 是什么。
  • @biziclop 我尝试使用 for statments ,类似这样: for (int i=0;i

标签: java hashmap


【解决方案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);

【讨论】:

  • 如果你在 recyclerview 中获得了像 subject .getsubject();在适配器类中应该如何实现
【解决方案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});
     }
}

【讨论】:

    【解决方案3】:

    是的,Map 接口将允许您将数组存储为值。这是一个非常简单的例子:

    int[] val = {1, 2, 3};
    Map<String, int[]> map = new HashMap<String, int[]>();
    map.put("KEY1", val);
    

    此外,根据您的用例,您可能需要查看guava 提供的Multimap 支持。

    【讨论】:

      【解决方案4】:

      如果您想为一个键存储多个值(如果我理解正确的话),您可以尝试 MultiHashMap(在各种库中可用,而不仅仅是 commons-collections)。

      【讨论】:

        【解决方案5】:

        如果您可以将 List 保存为该 Map 中的值而不是数组,您的生活将会轻松得多。

        【讨论】:

          【解决方案6】:

          您可以将对象存储在 HashMap 中。

          HashMap&lt;String, Object&gt; map = new HashMap&lt;String, Object&gt;();

          你只需要正确地把它扔回去。

          【讨论】:

            猜你喜欢
            • 2014-05-20
            • 1970-01-01
            • 1970-01-01
            • 2012-02-14
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多