Java ArrayList toString() Method
The toString() method converts an ArrayList object into a string.
The syntax of the toString() method is:
arraylist.toString()
Note:arraylist is an object of the ArrayList class.
Parameter Description:
- None
Return Value
Returns the string representation of arraylist.
Example
Convert ArrayList to String type:
Example
import java.util.ArrayList;
import java.util.Comparator;
class Main {
public static void main(String[] args){
// Create a dynamic array
ArrayList<String> sites = new ArrayList<>();
sites.add("Example");
sites.add("Google");
sites.add("Wiki");
sites.add("Taobao");
System.out.println("Website list: " + sites);
// Convert ArrayList to String type
String list = sites.toString();
System.out.println("String: " + list);
}
}
import java.util.Comparator;
class Main {
public static void main(String[] args){
// Create a dynamic array
ArrayList<String> sites = new ArrayList<>();
sites.add("Example");
sites.add("Google");
sites.add("Wiki");
sites.add("Taobao");
System.out.println("Website list: " + sites);
// Convert ArrayList to String type
String list = sites.toString();
System.out.println("String: " + list);
}
}
Executing the above program produces the following output:
网站列表: [Example, Google, Wiki, Taobao] String: [Example, Google, Wiki, Taobao]
In the above example, we created an array named sites.
Note this line:
String list = sites.toString();
We use the toString() method to convert the arraylist into a string. This method converts the entire arraylist into a String type.
Note: The ArrayList class does not have its own toString() method; it overrides the toString() method of the Object class.
Other Extensions
Java ArrayList