If you can just use one of these two types of output, you can do
if (inputList instanceof RandomAccess) {
The RandomAccess interface means that the implementation allows O (1) get operations.
The token interface used by the List implementation to indicate that they support fast (usually constant) random access. The main purpose of this interface is to allow universal algorithms to change their behavior in order to provide good performance when applied to random or sequential access lists.
In this way, your APIs allow clients to secure their inputs. They can be passed as a result of Collections.unmodifiableList(...) and be sure that it is not modified by other code.
If you really know that the input is a mutable list, you can clone() list and then clear() it. Both ArrayList and LinkedList have public clone() methods that can be accessed reflexively.
source share