在 Java 中创建异构列表列表

Creating heterogenous list of lists in Java

我有以下代码

        List<Integer> startnodes = ImmutableList.of(397251,519504,539122,539123,539124,539125);
        List<Integer> endnodes = ImmutableList.of(539126,539127,539142,539143,539144,539145);
        List<String> rp = ImmutableList.of("Knows","Knows","Knows","Knows2","Knows2","Knows2");
        Map<String,Value> parameters =
                  ImmutableMap.of("rels",ImmutableList.of(startnodes,endnodes,rp));

编译器在最后一行抛出以下错误。

Type mismatch: cannot convert from ImmutableMap<String,ImmutableList<List<? 
extends Object&Comparable<?>&Serializable>>> to Map<String,Value>

我主要的困惑是这里的键的值是一个异构列表,那么键的类型应该是什么才能满足编译器?。我对 Java 比较陌生,欢迎提出任何建议。谢谢!

ImmutableList.of(startnodes,endnodes,rp) 需要推断出一个同时满足 List<Integer>List<String> 的类型,因为 Java 中的泛型是 invariant 唯一满足它的类型是 List<?>。所以你可以将它分配给:

List<List<?>> list = ImmutableList.of(startnodes,endnodes,rp);

而您的 Map 需要定义为:

Map<String,List<List<?>>> parameters = ImmutableMap.of("rels",ImmutableList.of(startnodes,endnodes,rp));

您可以使用 ImmutableList.<Object>of(397251,519504,....) 创建相同类型的列表。这样你会得到一个同质的 ImmutableList<ImmutableList<Object>>,这可能比使用通配符更容易混淆。

然而,这一切都表明 List 不是解决您问题的正确方法。创建一个微小的 class 怎么样?使用龙目岛,你只需要

@lombok.Value public class Something {
    private final ImmutableList<Integer> startNodes;
    private final ImmutableList<Integer> endNodes;
    private final ImmutableList<String> rp;
}

如果没有 Lombok,您需要编写相当多的样板文件,但这可能仍然值得,因为处理异构列表很痛苦。