Java ArrayList to String

To convert an array list into a String, we can use the toString() method. For example,


\begin{lstlisting}
import java.util.ArrayList;
\par
class Main {
public static ...
...imals.toString();
System.out.println(''String: '' + str);
}
}
\end{lstlisting}

Output


\begin{lstlisting}
ArrayList: [Dog, Cat, Horse]
String: [Dog, Cat, Horse]
\end{lstlisting}

toString() converts the whole array list into a single String. Other ArrayList Methods:

  1. clone() & Creates a new array list with the same element, size, and capacity.
  2. contains() & Searches the array list for the specified element and returns a boolean result.
  3. ensureCapacity() & Specifies the total element the array list can contain.
  4. isEmpty() & Checks if the array list is empty.
  5. indexOf() & Searches a specified element in an array list and returns the index of the element.
  6. trimToSize() & Reduces the capacity of an array list to its current size.