2015-02-24 80 views
1

我要填写一个HashMap<Integer,Double[]>如何在添加到Map时将double数组添加到Double数组?

Map<Integer,Double[]> cached_weights = new HashMap<Integer,Double[]>(); 

只有定期intdouble[],什么是做到这一点的最好方法是什么?

我看到this question,但它回答了相反的问题。

+0

它被称为“拳击”。 – immibis 2015-02-24 03:47:15

+2

如果你想使用'int'类型作为键而不是'Integer',那么这是不可能的。另外'Double []'和'double []'不是协变的,'double []'不会被自动装箱到'Double []'。 – Pshemo 2015-02-24 03:47:32

+2

另外,'Double []'不是* boxed'double []'(装箱不适用于数组),并且您可以在hashmap中存储'double []'。 – immibis 2015-02-24 03:47:45

回答

1

对于键(Integer),编译器会自动为您处理,您可以直接传递一个int值。

对于布尔数组,你可以处理这种方式与Java 8

Map<Integer, Double[]> foo = new HashMap<Integer, Double[]>(); 
double[] bar = new double[10]; 
//As you can see, 1 is passed directly and will be converted to Integer object. 
foo.put(1, Arrays.stream(bar) 
      .boxed() 
      .toArray(Double[]::new)); 

DoubleStreamboxed方法返回一个包含该流的要素,盒装到双流。

然后你得到一个流,你可以轻松地呼叫toArray转换为Double[]