Search code examples
javalistoopinterface

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


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?


Solution

  • 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. 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 made up for theatrical effect :-)