What is the reverse of (ArrayList).toString for a Java ArrayList?

10,606

Solution 1

The short answer is "No". There is no simple way to re-import an Object from a String, since certain type information is lost in the toString() serialization.

However, for specific formats, and specific (known) types, you should be able to write code to parse a String manually:

// Takes Strings like "[a, b, c]"
public List parse(String s) {
  List output = new ArrayList();
  String listString = s.substring(1, s.length() - 1); // chop off brackets
  for (String token : new StringTokenizer(listString, ",")) {
    output.add(token.trim());
  }
  return output;
}

Reconstituting objects from their serialized form is generally called deserialization

Solution 2

Here's a similar question:

Reverse (parse the output) of Arrays.toString(int[])

It depends on what you're storing in the ArrayList, and whether or not those objects are easily reconstructed from their String representations.

Share:
10,606
user174772
Author by

user174772

Updated on June 04, 2022

Comments

  • user174772
    user174772 almost 2 years

    I am using the toString method of ArrayList to store ArrayList data into a String. My question is, how do I go the other way? Is there an existing method that will parse the data in the String instance back into an ArrayList?

  • Joachim Sauer
    Joachim Sauer over 14 years
    The List.toString() format is pretty different from JSON. In fact it's a lot simple (and a lot less powerful). Using a JSON library is overkill (and probably just wrong).
  • user174772
    user174772 over 14 years
    In this case, I was using strings, so I guess parsing it myself is simple enough. Thank you.
  • iny
    iny over 14 years
    Implementing own buggy parser is just wrong. Using tested library is much better, always.
  • Miserable Variable
    Miserable Variable over 14 years
    Of course, this would work only if the strings don't themselves contain the comma characters, which is the first point in my response.
  • Maarten Bodewes
    Maarten Bodewes over 9 years
    Personally I would create a Codec class for this, so it is possible to parameterize the class (later on) and check for specific good/bad encodings.
  • Salmaan
    Salmaan over 9 years
    What if my string in the arraylist contains ',' in it ?