Sort Elements of an ArrayList

To sort elements of an array list, we use the sort() method of the Collections class. In order to use it, we must import the java.util.Collections package first. By default, the sorting occurs either alphabetically or numerically in ascending order. For example,


\begin{lstlisting}
import java.util.ArrayList;
import java.util.Collections;
\pa...
...s);
System.out.println(''Sorted ArrayList: '' + animals);
}
}
\end{lstlisting}

Output


\begin{lstlisting}
Unsorted ArrayList: [Horse, Zebra, Dog, Cat]
Sorted ArrayList: [Cat, Dog, Horse, Zebra]
\end{lstlisting}