Java相当于来自Kotlin的arrayof()/ listof()/ setof()/ mapof()

jer*_*c05 4 java arrays list set

我只是想知道如果java具有与kotlin中的那些相同的arrayof()/ listof()/ setof()/ mapof()?如果没有,有没有办法同样工作?我发现它们与java非常不同.

顺便说一句,做intArrayOf()/ arraylistof()/ hashsetof()/ hashmapof()等做同样的事情int [] {}/new new ArrayList <>()/ new HashSet <>()/ new HashMap <> ()等?

Lui*_*oza 10

Java的9带来了类似的方法:List#of,Set#of,Map#of与几个重载方法,以避免调用可变参数之一.如果是Mapvarargs,你必须使用Map#ofEntries.

在Java 9之前,您必须将其Arrays#asList用作初始化的入口点,List并且Set:

List<String> list = Arrays.asList("hello", "world");
Set<String> set = new HashSet<>(Arrays.asList("hello", "world")); 
Run Code Online (Sandbox Code Playgroud)

如果你想要你的Set不可变,你必须将它包装在一个不可变的集合中Collections#unmodifiableSet:

Set<String> set = Collections.unmodifiableSet(
    new HashSet<>(Arrays.asList("hello", "world")));
Run Code Online (Sandbox Code Playgroud)

对于Map,您可以使用创建扩展Map实现的匿名类的技巧,然后将其包装在内部Collections#unmodifiableMap.例:

Map<String, String> map = Collections.unmodifiableMap(
    //since it's an anonymous class, it cannot infer the
    //types from the content
    new HashMap<String, String>() {{
        put.("hello", "world");
    }})
    );
Run Code Online (Sandbox Code Playgroud)