Valette_Renoux
Valette_Renoux

Reputation: 366

Can ArrayList.sort modify the list before throwing an exception?

I am trying to sort an ArrayList using the Collections.sort() method. However, my comparator does not fully respect the contract, and in some cases the sort method will throw an exception: java.lang.IllegalArgumentException: Comparison method violates its general contract!

My question is about the state of the list when this happens. Can it have already been modified (partially sorted)? Is it possible that it loses elements?

Upvotes: 1

Views: 363

Answers (1)

Eran
Eran

Reputation: 393906

Looking at the code of Collections.sort (which calls List.sort in Java 8), the sorting is performed on an array (using Arrays.sort), followed by assignment of the elements to the List in sorted order.

Therefore, any exception thrown during the sorting will prevent the List from being modified.

default void sort(Comparator<? super E> c) {
    Object[] a = this.toArray();
    Arrays.sort(a, (Comparator) c);
    ListIterator<E> i = this.listIterator();
    for (Object e : a) {
        i.next();
        i.set((E) e);
    }
}

BTW, this is a default implementation that appears in the List interface. If any List implementation overrides this implementation with an implementation that modifies the List before the sorting is done, the answer to your question can change.

Upvotes: 1

Related Questions