Java等效于Kotlin的arrayof()/listof()/setof()/mapof() [英] Java's equivalent of arrayof()/ listof()/ setof()/ mapof() from Kotlin
问题描述
我只是想知道java是否像kotlin一样具有arrayof()/listof()/setof()/mapof()?如果没有,是否有任何类似的工作方式? 我发现它们与Java非常不同. >
顺便说一句,做intArrayOf()/arraylistof()/hashsetof()/hashmapof()等与int [] {}/new new ArrayList<>()/new HashSet<>()/new HashMap<>()等?
Java 9带来了类似的方法: Set#of
, Map#ofEntries
.
在Java 9之前的版本中,您必须使用Arrays#asList
作为初始化List
和Set
的入口点:
List<String> list = Arrays.asList("hello", "world");
Set<String> set = new HashSet<>(Arrays.asList("hello", "world"));
如果您希望 对于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: Pre Java 9, you had to use And if you wanted your For Map, you may use a trick creating an anonymous class that extended a
这篇关于Java等效于Kotlin的arrayof()/listof()/setof()/mapof()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!Set
是不可变的,则必须将其包装在Map
实现的匿名类,然后将其包装在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
.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"));
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")));
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");
}})
);