简体   繁体   English

Map.of 为 Java 在 Scala

[英]Map.of for Java in Scala

How to call static varg overloads of java Map from Scala?如何从 Z3012DCFF1477E1FEAAB81764 调用 java Map的 static varg 过载?

for ex:例如:

 val map: java.util.Map[Char,Int] =
  java.util.Map.of('Z', 5, 'R', 2, 'X', 9, 'A', 4, 'F', 1)

This fails with Error as Scala treats of as member of Map.这失败并出现错误,因为 Scala 将其视为 Map 的成员。

    Value of is not a member of object java.util.Map
          java.util.Map.of('Z', 5, 'R', 2, 'X', 9, 'A', 4, 'F', 1)
                        ^Compilation Failed 

Note that Map.of was introduced with Java SE 9 and therefore your code will fail to compile with pre-Java9 JDK.请注意, Map.of是随Java SE 9引入的,因此您的代码将无法使用 Java9 之前的 JDK 进行编译。

Another important fact you should keep in mind is that using Map.of , you can store a maximum of 10 entries only, and for each number of entries (zero to 10), there is a separate Map.of defined.您应该记住的另一个重要事实是,使用Map.of最多只能存储 10 个条目,并且对于每个条目数(0 到 10),定义了一个单独的Map.of So, it's NOT a varg.所以,它不是一个 varg。

eg the following statement is correct例如以下陈述是正确的

Map<Character, Integer> map = Map.of('A', 1, 'B', 2, 'C', 3, 'D', 4, 'E', 5, 'F', 6, 'G', 7, 'H', 8, 'I', 9,
                'J',  10);

but NOT the following one:不是以下一个:

Map<Character, Integer> map = Map.of('A', 1, 'B', 2, 'C', 3, 'D', 4, 'E', 5, 'F', 6, 'G', 7, 'H', 8, 'I', 9,
                'J', 10,'K',11);

If you want to store more than 10 entries using a single statement like this, you can use Map#ofEntries .如果您想使用这样的单个语句存储超过 10 个条目,则可以使用Map#ofEntries

Demo:演示:

import static java.util.Map.entry;

import java.util.Map;

public class Main {
    public static void main(String[] args) {
        Map<Character, Integer> map = Map.ofEntries(entry('A', 1), entry('B', 2), entry('C', 3), entry('D', 4),
                entry('E', 5), entry('F', 6), entry('G', 7), entry('H', 8), entry('I', 9), entry('J', 10),
                entry('K', 11));

        System.out.println(map);
    }
}

Output: Output:

{K=11, J=10, I=9, H=8, G=7, F=6, E=5, D=4, C=3, B=2, A=1}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM