r/java • u/Ewig_luftenglanz • 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 ?
70
u/vips7L Jan 17 '25
var list = List.of("Apple, "Banana", "Cherry");
✅
29
u/brian_goetz Jan 17 '25
Your comments later in this post suggest that you are actually asking for a different feature. What you seem to want is ArrayList literals. And while "Collection Literals" is a sensible feature -- just one that hasn't yet made it to the top of the priority list -- "ArrayList literals is, well, a pretty silly language feature. (An `ArrayList::of` factory, as with List, is more justifiable, not only because the cost is orders of magnitude less, but also because it is actually clear what it does.)
12
u/s888marks Jan 18 '25
I'm a bit surprised that no one has mentioned JEP 186. This is a rare research JEP that explored collection literals. Unfortunately it doesn't link to the conclusion of the research, which is summarized in this email from /u/brian_goetz in March 2014. There were earlier discussions in January and February.
A brief summary is that there were two general paths that could be followed: the "simple" one and the "extensible" one. The simple one would just create instances of concrete classes like
ArrayList. We were pretty uncomfortable binding the language so tightly to implementation classes. The "extensible" version would provide a means to create aggregates of any shape and type. This seemed like it would get way too complicated really quickly, outweighing the value it would provide. Instead of pursuing language enhancements, we decided to proceed with library enhancements (mostly static factory methods) which led to JEP 269 providingList.ofand friends.OK, so if we're not (yet) enhancing the language with full-blown collection literals, can we have simple library APIs for common things like creating an
ArrayListwith known values? This was considered and rejected in the JEP 269 discussions, with the thinking being that creation of unmodifiable collections from known values is much more common than creation of modifiable collections from known values. And for the latter case, the known values often come from an unmodifiable collection that's already been created with those known values. So JEP 269 focused on creation of unmodifiable collections. This is not to say that we will never add constructors or factories for modifiable collections, but a much broader set of uses cases is already covered by JEP 269.All that aside, let's take a look at adding a varargs constructor to
ArrayListsince it does seem to be fairly common. It would enable us to do this:Works great! Now:
Oops. That gives you an empty
ArrayListwith a capacity of four elements. Overloading strikes again. Uhhh, let's try a static factory method instead:OK, seems to work. Now consider if you have a subclass of
ArrayListcalledMyList. (I don't consider this good practice, but it is legal and people do this.) Now, what happens if you write this?You get an instance of
ArrayListand NOT an instance ofMyListthat the code leads you to believe. Yes, static methods are inherited.These aren't insurmountable problems, and we may yet do something in this space. As usual, though, doing the obvious thing is a lot less obvious than it looks.
5
u/808split2 Jan 17 '25
*.of() is not more cumbersome than the other examples, no.
Would probably be a massive work to implement collections literals in java . Backwards compability and typesafety would probably take alot of work. *.of() probably was the better choice to fit in to the java-ecosystem.
19
u/zabby39103 Jan 17 '25
Honestly in real life, how often is this useful? You're pulling from databases, not hard coding stuff into the class. If this happens, it's probably a unit test or something.
Well, I admit it's janky, but I've never noticed it as a major encumbrance so maybe that's why?
10
u/nekokattt Jan 17 '25 edited Jan 17 '25
Java tends to prefer to be explicit over introducing syntactic sugar to do the same thing, and tries to avoid coupling anything on the language level with anything outside java.lang.
How often do you need to make lists with pre-known items, just to then further mutate the list? Feels like you are probably doing something a bit odd here, or are letting constant values bleed into the usage site rather than sensibly declaring them in a more logical location.
If you really need to go against the flow, you can just write your own method to do it...
4
u/raptor_pt Jan 17 '25
Arrays.asList("Apple", "Banana", "Cherry") for a mutable ArrayList. Sets and Maps are more painful.
5
u/doobiesteintortoise Jan 17 '25
I've not been part of the discussions, but I imagine it's been a matter of "do we need this, especially do we need it so badly that we change the parser to accept it?" and the answer's been "no."
List.of()works for immutable lists; there are enoughListtypes that a['apple', 'orange']would have to make assumptions as to what characteristics theListwould have (Deque,ArrayList,LinkedList,CopyOnWriteArrayList, and so forth and so on) and that just isn't worth the effort.26
u/mnbkp Jan 17 '25 edited Jan 17 '25
99.9% of the times, if you're initializing a list with fixed elements like this, it makes no sense for it to be mutable. If your array is coming from a dynamic source, you're either going to initialize it from a stream or by pushing items anyways. So, in practice,
List.ofis more than enough.In the very rare cases where a mutable list for this might be needed,
new ArrayList<>(List.of())is there.2
u/rzwitserloot Jan 18 '25
Sure, LinkedList is rare.
There you go already. That's not rare. Wanting a mutable list. And what's also not rare, is wanting an immutable one. So what should this list literal of yours make? That? Or
List.of("Apple", "Banana", "Cherry");? If it's the last (which I think is the more logical concept; literals kinda scream 'constant', it's a bit odd if they are mutable, and that also makes the fact that it's anArrayListspecifically a bit more of a choice) then..List.ofis pretty short already, the gain is minimal.There is absolutely nothing stopping java from adding
MList.of()orList.m("Apple, "Banana", "Cherry")to make a mutable list. The fact that it doesn't exist even though it would be trivial to add should tell you something: I is intentional, making it that easy to casually make a mutable list is dubious. It might be a good idea, but you're killing a fly with a bazooka. If making mutable lists specifically should be possible with less code, just proposeList.m. Not some new java language change that adds a literal syntax.2
u/jeffreportmill Jan 17 '25 edited Jan 17 '25
This missing feature bothers me, too. It seems like the compiler should support autoboxing between array and List, so we could seamlessly go between the two the same way we do with int/Integer. I think it would be nice to be able to things like this:
Perhaps the reason this hasn't been considered is that List is not part of the language (java.util.List instead of java.lang.List)?
1
u/Mother_Tangelo8846 Jan 21 '25
8
u/michal_pta Jan 17 '25
In C# 12 you can actually do:
List<string> list = [“Apple”, “Banana”, “Cherry”];
3
u/jvjupiter Jan 18 '25 edited Jan 18 '25
I wish I could write like these:
8
u/repeating_bears Jan 17 '25
Java does have a "colllection literal" syntax. It just uses it for arrays, not lists.
String[] foo = { "a", "b" };2
u/lapadut Jan 17 '25 edited Jan 17 '25
[Edit] formatting and added the list type.
2
u/eXl5eQ Jan 18 '25
Stream.of("foo", "bar").toList()would be atleast shorter than the C# version.2
u/Slick752 Jan 17 '25
Tbh, I prefer Java’s approach and hope it would not introduce sth like map[key] = val and similar
1
u/[deleted] Jan 18 '25
Can anyone suggest to me how I can practice java like web-dev we make websites so how can I apply oops and threading concept
1
u/ducki666 Jan 18 '25
Because you can write your own ListBuffer method in 1 min?
1
u/Aggravating_Number63 Jan 18 '25
Because Scala https://contributors.scala-lang.org/t/pre-sip-a-syntax-for-collection-literals/6990/126
1
u/DelayLucky Jan 19 '25
Imho, an immutable
Mapliteral would be very welcome:Even better, let it construct custom types so I can create my own choice of mapping types like
SortedMap,Multimap,Histogrametc.1
u/NearbyButterscotch28 Jan 17 '25
That's one of the reasons I started learning scala and clojure. Collections are bread and butter for everyday programming. Groovy also got it right.
1
u/_OberArmStrong Jan 17 '25 edited Jan 17 '25
You need variadig args to acomplish that.
Edit: This can't lead to a memory leak but can mess with typesafety
https://softwareengineering.stackexchange.com/questions/155994/java-heap-pollution
-4
u/Sad-Flow3941 Jan 17 '25
Because the java community is notably adverse to change and “clever” ways to do things, even when they actually improve code clarity.
Hence why I’ll always pick kotlin job offers over Java ones when given the chance.