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.?
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[].
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.
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.
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");
}})
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With