Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.?

like image 551
jerryc05 Avatar asked May 24 '18 15:05

jerryc05


People also ask

What is the difference between Arrayof and listOf in Kotlin?

Array is of fixed size. It cannot increase and decrease in size. MutableList<T> do have 'add' and 'remove' functions in order to increase or decrease the size of the MutableList. Use it for better performance, as array is optimized for different primitive data types such as IntArray[], DoubleArray[].

What is Arrayof in Java?

Java array is an object which contains elements of a similar data type. Additionally, The elements of an array are stored in a contiguous memory location. It is a data structure where we store similar elements. We can store only a fixed set of elements in a Java array.

How do I make a List string in Kotlin?

To define a list of Strings in Kotlin, call listOf() function and pass all the Strings as arguments to it. listOf() function returns a read-only List. Since, we are passing strings for elements parameter, listOf() function returns a List<String> object.


1 Answers

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");
    }})
    );
like image 138
Luiggi Mendoza Avatar answered Sep 17 '22 08:09

Luiggi Mendoza