同时尝试使用 Vavr的不可变映射 (io.vavr.collection.HashMap
) 与 java.util.Map
接口(interface),我没有设法编译代码 - 至少没有通过使用 io.vavr.collection.HashMap
中的 .of()
静态方法。
本质上这是我正在使用的 Maven 依赖项:
<dependency>
<groupId>io.vavr</groupId>
<artifactId>vavr</artifactId>
<version>0.9.2</version>
</dependency>
使用 Java 1.8
这是代码:
import io.vavr.collection.HashMap;
import java.util.Map;
public class EntityKeyMap {
public static final Map<String, String> map =
HashMap.of("key1", "val1", "key2", "val2", "key3", "val3");
private EntityKeyMap() {
}
}
这是我遇到的错误:
Incompatible types. Required Map but 'of' was inferred to HashMap: no instance(s) of type variable(s) K, V exist so that HashMap conforms to Map
关于如何将 io.vavr.collection.HashMap
的实例分配给 java.util.Map
的任何想法?这可能吗?
根据 io.vavr.collection.HashMap
文档,它实现了 java.util.Map
接口(interface):
https://static.javadoc.io/io.vavr/vavr/0.9.2/io/vavr/collection/HashMap.html
网上有一些例子似乎是可行的,比如这个 blog在哪里可以找到此代码:
Map<String, String> map1
= HashMap.of("key1", "val1", "key2", "val2", "key3", "val3");
最佳答案
Vavr 的 HashMap
没有实现 JDK's Map
界面。它实现的Map
接口(interface)是vavr's own Map
界面。
与JDK 的Map
相比,vavr 的Map
表示一个不可变 映射,HashMap
是基于 Hash array mapped trie 的高效持久 map 实现.
JDK Map
接口(interface)和 vavr Map
接口(interface)之间最根本的区别在于 JDK map 具有改变 map 内部的方法state,而 vavr 的方法总是返回一个新的 Map
实例(或者相同的实例,以防 map 没有改变)。
比较 JDK 的 Map.put
vs vavr 的 Map.put
方法签名。
JDK Map.put
:
V put(K key, V value)
Associates the specified value with the specified key in this map (optional operation). If the map previously contained a mapping for the key, the old value is replaced by the specified value. (A map m is said to contain a mapping for a key k if and only if m.containsKey(k) would return true.)
Returns: the previous value associated with key, or null if there was no mapping for key. (A null return can also indicate that the map previously associated null with key, if the implementation supports null values.)
vavr Map.put
:
Map<K,V> put(K key, V value)
Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced by the specified value.
Returns: A new Map containing these elements and that entry.
如果需要JDK Map,可以用Map.toJavaMap
转换vavr map ,但这将创建 map 内容的完整副本,因为 JDK map 的可变性质与 vavr 的不可变方法不兼容。
关于java - 是否可以将 map 接口(interface)与 io.vavr.collection.HashMap 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51980983/