r/java • • Mar 16 '21

Java 16 / JDK 16: General Availability

196 Upvotes

82 comments sorted by

View all comments

65

u/[deleted] Mar 16 '21

Finally I can start migrating from .collect(Collectors.toList()) to toList()

21

u/TheCountRushmore Mar 16 '21

Keep in mind that toList() returns an immutable list, but this might be exactly what you want.

14

u/kag0 Mar 16 '21

I really wish they hadn't implemented "immutable" lists as a normal List that throws unchecked exceptions on modification.

Would it have been that hard to add a ReadOnlyList interface with only the methods that don't throw? Now we've got a wonky compile-unsafe toList() in the standard library for all time.

4

u/rbygrave Mar 17 '21

This was discussed when the Collections API was first designed and the idea was rejected at the time. I believe the reasons were due to the "relative explosion" in number of interfaces in the Collections API.

I'll see if I can find a reference ...

Ah, its discussed in the javadoc - https://docs.oracle.com/javase/6/docs/technotes/guides/collections/designfaq.html#1

A snippet from there:

Why don't you support immutability directly in the core collection interfaces so that you can do away with optional operations (and UnsupportedOperationException)?

This is the most controversial design decision in the whole API. Clearly, static (compile time) type checking is highly desirable, and is the norm in Java. We would have supported it if we believed it were feasible. Unfortunately, attempts to achieve this goal cause an explosion in the size of the interface hierarchy, and do not succeed in eliminating the need for runtime exceptions (though they reduce it substantially).