To convert an ArrayList
to a string in Java, you can use the toString()
method of the ArrayList
class or the join()
method of the String
class.
Here is an example of how to convert an ArrayList
to a string using the toString()
method:
import java.util.ArrayList; public class ArrayListToStringExample { public static void main(String[] args) { ArrayList<String> words = new ArrayList<>(); words.add("hello"); words.add("world"); words.add("goodbye"); words.add("moon"); String str = words.toString(); System.out.println(str); } }
This code creates an ArrayList
of strings called words
and adds some elements to it. It then calls the toString()
method of the words
list and assigns the returned string to the str
variable. The toString()
method returns a string representation of the ArrayList
, containing the elements of the list separated by commas and enclosed in square brackets.
The toString()
method is inherited from the Object
class and is overridden in the ArrayList
class to return a string representation of the list. It is a useful method for debugging and logging, but it may not always produce the desired string format.
If you want to convert an ArrayList
to a string with a custom format, you can use the join()
method of the String
class. The join()
method takes a delimiter string and an iterable object as arguments and returns a string consisting of the elements of the iterable joined by the delimiter.
Here is an example of how to convert an ArrayList
to a string using the join()
method:
String str = String.join(", ", words);
This code calls the join()
method with the delimiter ", " and the words
list as arguments and assigns the returned string to the str
variable. The join()
method returns a string containing the elements of the words
list separated by ", " (a comma followed by a space).
You can also use the join()
method with a StringBuilder
to build the string more efficiently if you need to concatenate many strings.