In Java, to reverse elements in a List, I need to use:
Why is there no
List.reverse()method in Java?
Because there is a
Collections.reverse(List) method instead.
Because the API designers figured it was a bad idea to force every
List implementation1 to implement a method that wasn't used 99.9% of the time2. This could be addressed by making the method "optional", but that has downsides too; e.g. runtime exceptions.
Because for some kinds of list (stream wrappers / adapters for example) implementing in-place reverse would be problematic. It changes the memory usage characteristics of the list by requiring it to be reified.
Also note that the generic implementation (source code) of
reverse() that is provided by
set to swap elements. It is close to optimal for the standard list types.
I assume OP is asking why it wasn't added as a default method, as List.sort() was.
Good question. Possibly the 99.9% argument applies. Bear in mind that this would only help people with a codebase that is built using a Java 8 or later compilers, etc.
1 - This includes implementations in your codebase and 3rd-party libraries.
2 - 86% of statistics are are made up for theatrical effect :-)