In Java, to reverse elements in a List, I need to use:
Collections.reverse(list)
I was just wondering why Java doesn't implement the reverse method within the List
interface so that I could do the in-place reverse like this:
list.reverse()
Does anyone have any ideas about this?
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 Collection
uses set
to swap elements. It is close to optimal for the standard list types.
@shmosel comments:
I assume OP is asking why it wasn't added as a default method, as
List.sort()
was.
Good point. Possibly the 99.9% argument applies. Also, this would only help people with applications that target Java 8 or later.
However, there is the problem that the List
API can be used for lazy lists3:
If an application naively tried to call a (hypothetical) default List.reverse()
method on a lazy list ("because it ought to work") it could end up causing an OOME or excessive memory use. (The correct solution is for a lazy list class to override the default method, but that implies that adding the default method is breaking backwards compatibility.)
1 - This includes implementations in your codebase and 3rd-party libraries.
2 - 86% of statistics are made up for theatrical effect :-)
3 - For example: https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/list/LazyList.html