How to Convert a List to a String in Java

The Java programming language stores list values in a data type called an "ArrayList." These ArrayList objects can be converted to a string that lists each value contained inside the array. Although a string object does not contain the sorting, indexing and modification capabilities of an ArrayList, it is useful for quickly displaying the entire contents of the object to a user or printing the state of a list object to a debugging file.

Instructions

    • 1

      Open your Java application in your preferred text editor and navigate to the point of your code where the ArrayList object is created.

    • 2

      Locate the declaration of your ArrayList or create it if you have not already done so. For example, type the following code to create a new ArrayList named "testList" with three elements using the following code:

      ArrayList testList = new ArrayList();

      testList.add("Value1");

      testList.add("Value2");

      testList.add("Value3");

    • 3

      Convert the ArrayList's contents into a new string using the ArrayList's built-in "toString()" command. Type the following code on its own line to store a String representation of "testList" in a variable called "testString."

      String testString = testList.toString();

Tips & Warnings

  • Write your output string to the console using the System.out.println function.

Related Searches:

References

Comments

Related Ads

Featured