Hanfei Sun Hanfei Sun - 3 years ago 136
Java Question

Why is there no "List.reverse()" method in Java?

In Java, to reverse elements in a List, I need to use:


I was just wondering why Java doesn't implement the reverse method within the
interface so that I could do the in-place reverse like this:


Does anyone have any ideas about this?

Answer Source

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.

@smhomsel comments:

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 :-)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download