Java's equivalent of arrayof()/ listof()/ setof()/ mapof() from Kotlin

后端 未结 1 1670
忘了有多久
忘了有多久 2021-01-18 09:25

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

1条回答
  •  [愿得一人]
    2021-01-18 10:15

    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 list = Arrays.asList("hello", "world");
    Set 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 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 map = Collections.unmodifiableMap(
        //since it's an anonymous class, it cannot infer the
        //types from the content
        new HashMap() {{
            put.("hello", "world");
        }})
        );
    

    0 讨论(0)
提交回复
热议问题