2012-02-26 82 views
7

我有一个长处理的结果。我不想直接将它传递给HashMap并做更多的计算。我想保存它,然后每次重新使用。用项目数组初始化HashMap?

我的价值观的阵列看起来像这样:

{0=0, 1=15, 2=70, 3=90, 4=90, 5=71, 6=11, 7=1, 8=61, 9=99, 10=100, 11=100, 12=100, 13=66, 14=29, 15=98, 17=100, 16=100, 19=100, 18=100, 21=62, 20=90, 23=100, 22=100, 25=100, 24=100, 27=91, 26=100, 29=100, 28=68, 31=100, 30=100, 34=83, 35=55, 32=100, 33=100, 38=100, 39=100, 36=100, 37=100, 42=10, 43=90, 40=99, 41=33, 46=99, 47=40, 44=100, 45=100, 48=2} 

有没有一种方法来初始化通过将这些值的新的HashMap?也许像初始化一个简单的数组:

float[] list={1,2,3}; 
+1

密钥是否真的是连续的整数? – 2012-02-26 13:41:12

+0

数组中值的类型是什么?地图的键和值的类型应该是什么? – 2012-02-26 13:41:29

+0

@BorisStrandjev是的,它们是之前HashMap的内容println'ed – Andrew 2012-02-26 13:41:50

回答

8

因为你把我们的盈方的问题,最好的解决办法是:

int [] map = 
    {0, 15, 70, 90, 90, 71, 11, 1, 61, 99, 100, 100, 100, 66, 29, 98, 100, 100, 
    100, 100, 90, 62, 100, 100, 100, 100, 100, 91, 68, 100, 100, 100, 100, 100, 
    83, 55, 100, 100, 100, 100, 99, 33, 10, 90, 100, 100, 99, 40, 2}; 

这是一种地图毕竟 - 它将索引映射到相应的值。但是,如果您的密钥不是特定的,您可以执行类似操作:

int [][] initializer = 
    {{0, 0}, {1, 15}, {2, 70}, {3, 90}, {4, 90}, {5, 71}, {6, 11}, {7, 1}, {8, 61}, 
    {9, 99}, {10, 100}, {11, 100}, {12, 100}, {13, 66}, {14, 29}, {15, 98}, 
    {17, 100}, {16, 100}, {19, 100}, {18, 100}, {21, 62}, {20, 90}, {23, 100}, 
    {22, 100}, {25, 100}, {24, 100}, {27, 91}, {26, 100}, {29, 100}, {28, 68}, 
    {31, 100}, {30, 100}, {34, 83}, {35, 55}, {32, 100}, {33, 100}, {38, 100}, 
    {39, 100}, {36, 100}, {37, 100}, {42, 10}, {43, 90}, {40, 99}, {41, 33}, 
    {46, 99}, {47, 40}, {44, 100}, {45, 100}, {48, 2}}; 
Map<Integer, Integer> myMap = new HashMap<Integer, Integer>(); 
for (int i = 0; i < initializer.length; i++) { 
    myMap.put(initializer[i][0], initializer[i][1]); 
} 
2

的唯一方法来初始化值的HashMap是创建对象后使用put()方法多次。这是因为HashMap需要执行哈希机制来正确地对映射中的对象进行排序,以实现其保证的性能。

1

据我所知,你不能像数组那样容易地实例化一个HashMap。

你可以做什么,是写一个utitlity方法并用它来实例化一个地图:

Map<Integer, Integer> createMap(Integer[] array) { 
    Map<Integer, Integer> map = new HashMap<Integer, Integer>(); 
    for(int i = 0; i < array.length; i++) { 
     map.put(i, array[i]); 
    } 
    return map; 
} 
2

你提的问题是非常混乱。它想要将地图的内容复制到另一个地图,请使用putAll方法。

Map<Integer, Integer> newMap = new HashMap<Integer, Integer>(); 
newMap.putAll(oldMap); 

,或者直接拷贝构造函数:

Map<Integer, Integer> newMap = new HashMap<Integer, Integer>(oldMap); 
+0

或使用构造函数:'HashMap(Map <?extends K,?extends V> m)':) – 2012-02-26 13:48:44

+0

当然。我将编辑我的答案:-) – 2012-02-26 13:51:55

+0

什么数据类型是oldMap? – 2014-10-02 17:55:32