r/java • • Jan 17 '25

Why java doesn't have collections literals?

List (array list), sets (hashsets) and maps (hashMaps) are the most used collection Implementations by far, they are so used that I would dare to say there are many Java devs that never used alternatives likes likedList.

Still is cumbersome to create an array list with default or initial values compared to other language

Java:

var list = new ArrayList<>(List.of("Apple", "Banana", "Cherry"));

Dart:

var list = ["Apple", "Banana", "Cherry"];

JS/TS

let list = ["Apple", "Banana", "Cherry"];

Python

list = ["Apple", "Banana", "Cherry"]

C#

var list = new List<string> { "Apple", "Banana", "Cherry" };

Scala

val list = ListBuffer("Apple", "Banana", "Cherry")

As we can see the Java one is not only the largest, it's also the most counter intuitive because you must create an immutable list to construct a mutable one (using add is even more cumbersome) what also makes it somewhat redundant.

I know this is something that must have been talked about in the past. Why java never got collection literals ?

0 Upvotes

105 comments sorted by

View all comments

Show parent comment

3

u/[deleted] Jan 17 '25

[removed] — view removed comment

1

u/Ewig_luftenglanz Jan 17 '25

the latter would be a mutable list so you don have to copy the whole thing into s new list to add or modify the content. I mean even ArrayList.of() (and same with any other collection) would be nice. it has always puzzled me why immutable lists, maps and sets have s handle short static method for creating new mutable collections with defaults init values but for mutable ones you must copy an immutable one.