1

Java 9 introduced new convenience factory methods for creating Collections. As an example:

List<String> list = List.of("a", "b", "c");

Why results of these methods are immutable?

Mahozad
  • 18,032
  • 13
  • 118
  • 133
  • A better question to ask would be: "why would they produce the mutable ones?" – Nikolas Charalambidis Jul 02 '18 at 16:20
  • Usually people want immutable collections. It's also safer to use them, if you don't intend to change something. Another great thing is that an immutable structure greatly benefits from this knowledge and can be optimized heavily. For example a `Set` with only one element would have an enormous overhead if constructed with a usual `HashSet`. Compare that to an implementation that only has one field for that element and that's it. – Zabuzard Jul 02 '18 at 16:26
  • @Zabuza for Map it is the opposite tho, it uses just Object[2*size] and uses a loop to find value. Probably because most of such collections are pretty small, but not always... – GotoFinal Jul 03 '18 at 08:30
  • @GotoFinal I'm not sure I get what you are saying. An immutable `Map` can use the knowledge in the same way a `Set` can do (in fact both are conceptional the same, map just has a payload per entry, javas `HashSet` is indeed implemented as `HashMap` internally). Take a map with 5 entries for example. It is way faster to just hold all entries in an array and iterate them instead of computing hashes and maintaining hash tables or a tree structure. Just because arrays are super optimized (benefit from stuff like cache locality etc). Also you don't need any overhead related to rehashing etc. – Zabuzard Jul 03 '18 at 10:33
  • @Zabuza and then imagine generated map with 10000 entries and "converted" to immutable via `Map.copyOf` – GotoFinal Jul 03 '18 at 10:48
  • @GotoFinal A map with that size will of course not use the technique which is good for small collections. It will have a hash table with a well distributed hash-method and drop the rehashing code since rehashing is never needed for immutable collections. So you can still benefit from the knowledge. – Zabuzard Jul 03 '18 at 10:57

0 Answers0