Java等效于Kotlin的arrayof()/listof()/setof()/mapof() [英] Java's equivalent of arrayof()/ listof()/ setof()/ mapof() from Kotlin

查看:795
本文介绍了Java等效于Kotlin的arrayof()/listof()/setof()/mapof()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想知道java是否像kotlin一样具有arrayof()/listof()/setof()/mapof()?如果没有,是否有任何类似的工作方式? 我发现它们与Java非常不同.

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

解决方案

Java 9带来了类似的方法:

如果您希望Set是不可变的,则必须将其包装在

对于Map,您可以使用技巧创建一个扩展Map实现的匿名类,然后将其包装在

I was just wondering that if java has the equivalent of arrayof()/ listof()/ setof()/ mapof() like those in kotlin? If not, is there any way to work similarly? I found them very different from java.

Btw, do intArrayOf()/ arraylistof()/ hashsetof()/ hashmapof() etc. do the same thing as int[]{}/ new new ArrayList<>()/ new HashSet<>()/ new HashMap<>() etc.?

解决方案

Java 9 brings similar methods: List#of, Set#of, Map#of with several overloaded methods to avoid calling the varargs one. In case of Map, for varargs, you have to use Map#ofEntries.

Pre Java 9, you had to use Arrays#asList as entry point to initialize List and Set:

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

And if you wanted your Set to be immutable, you had to wrap it inside an immutable set from Collections#unmodifiableSet:

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

For Map, you may use a trick creating an anonymous class that extended a Map implementation, and then wrap it inside Collections#unmodifiableMap. Example:

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");
    }})
    );

这篇关于Java等效于Kotlin的arrayof()/listof()/setof()/mapof()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆