What is the reverse of (ArrayList).toString for a Java ArrayList?
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.
user174772
Updated on June 04, 2022Comments
-
user174772 almost 2 years
I am using the
toString
method ofArrayList
to storeArrayList
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 theString
instance back into anArrayList
? -
Joachim Sauer over 14 yearsThe 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 over 14 yearsIn this case, I was using strings, so I guess parsing it myself is simple enough. Thank you.
-
iny over 14 yearsImplementing own buggy parser is just wrong. Using tested library is much better, always.
-
Miserable Variable over 14 yearsOf 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 over 9 yearsPersonally 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 over 9 yearsWhat if my string in the arraylist contains ',' in it ?