将数组存储在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> map = new HashMap>(); HashMap map = new HashMap();
例如,选择一个
HashMap> map = new HashMap>(); map.put("Something", new ArrayList ()); for (int i=0;i
要不就
HashMap map = new HashMap(); map.put("Something", coeficientUzura);
不确定确切的问题,但这是你在寻找什么?
public class TestRun { public static void main(String [] args) { Map prices = new HashMap(); prices.put("milk", new Integer[] {1, 3, 2}); prices.put("eggs", new Integer[] {1, 1, 2}); } }
是的,Map接口允许您将Arrays存储为值。 这是一个非常简单的例子:
int[] val = {1, 2, 3}; Map map = new HashMap(); map.put("KEY1", val);
此外,根据您的使用情况,您可能希望查看番石榴提供的Multimap支持。
如果你想为一个键存储多个值(如果我理解正确的话),你可以尝试一个MultiHashMap (在各种库中都可用,不仅仅是commons-collections)。
如果您可以将List保存为该值而不是该Map中的数组,那么您的生活会更容易。
您可以将对象存储在HashMap中。
HashMap
你只需要正确地把它丢掉。