java - 是否可以将 map 接口(interface)与 io.vavr.collection.HashMap 一起使用?

标签 java vavr

同时尝试使用 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/

相关文章:

java - 使用 JSch 0.1.48 时出现 AuthFail 异常,但在 0.1.49 及更高版本中使用密码身份验证时不会出现异常

java - hibernate 一对一双向不工作

java - 具有泛型的 Vavr 给出了不兼容的类型

java - Vavr Set 字段应该是 volatile 的、原子性的还是以其他方式声明的?

java - 如何使用可选项实现这个嵌套流程?

java - 语言理论 - 循环不变量 - 前置/后置条件

java - Tomcat 6 启动时的警告和错误

java - 计划的可运行对象在启动时仅调用一次

spring - 使用 RestTemplae 获取 vavr Multimap 后的反序列化错误

java - 使用 VAVR 将 map 列表转换为单个 map