Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays Scala:附加到哈希映射中的值数组的末尾_Arrays_Scala_Hashmap_Append_Type Mismatch - Fatal编程技术网

Arrays Scala:附加到哈希映射中的值数组的末尾

Arrays Scala:附加到哈希映射中的值数组的末尾,arrays,scala,hashmap,append,type-mismatch,Arrays,Scala,Hashmap,Append,Type Mismatch,基本上,如果键不在映射中,我想用temp值将该值设置为一个新数组,如果键已经在映射中,我想将temp附加到现有数组的末尾。temp是一个整数 执行上述代码时,我遇到以下错误: var temp = 5 val map = new HashMap[String,Array[Integer]]() if(map contains str1){ map(str1) = map(str1) :+ temp }else{ map(str1) = Array(temp) } 我是新的scala

基本上,如果键不在映射中,我想用temp值将该值设置为一个新数组,如果键已经在映射中,我想将temp附加到现有数组的末尾。temp是一个整数

执行上述代码时,我遇到以下错误:

var temp = 5
val map = new HashMap[String,Array[Integer]]()
if(map contains str1){
   map(str1) = map(str1) :+ temp
}else{
   map(str1) = Array(temp)
}

我是新的scala,所以我完全不知道为什么会发生这种情况。谢谢你的帮助

此代码有两个问题。首先,我假设您使用的是可变HashMap,否则您将无法更新它

首先,由于声明了HashMap[String,Array[Integer]],但试图向数组[Integer]追加Int,因此出现编译错误。它们不是一回事。因此,编译器将类型推断为Any,这是不允许的,因为数组的type参数是不变的

因此,将声明更改为val map=newhashmap[String,Array[Int]]。在scala中使用整数没有太多理由。如果您真的需要使用val temp=new Integer5

在第一个编译器中,您尚未看到的第二个问题是,这将不起作用:

helloworld.scala:21: error: type mismatch;
 found   : Array[Any]
 required: Array[Integer]
Note: Any >: Integer, but class Array is invariant in type T.
You may wish to investigate a wildcard type such as `_ >: Integer`. (SLS 3.2.10)

                        map(str1) = (map(str1) :+ temp)
                                               ^
如果HashMap上不存在str1键,则调用mapstr1将引发异常,因此不能以这种方式分配新键。相反,您必须将键值对添加到映射中,如下所示:

map(str1) = Array(temp)

什么是临时工?你是怎么声明的?它是一个整数。i、 e.var temp=5感谢您的帮助。不相关,但是你知道为什么在scala中大数的立方体是负数吗?i、 e.10212*10212*10212=-194041280@user270104032位整数溢出。
map += (str1 -> Array(temp))