views:

696

answers:

4

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 back into an ArrayList?

A: 

I would recommend using some standard format with a library for it instead.

JSON is probably the closest syntactically.

Alternatively some XML or serialization based solution could work too. It all depends on your needs of course.

iny
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).
Joachim Sauer
Implementing own buggy parser is just wrong. Using tested library is much better, always.
iny
+1  A: 

Here's a similar question:

http://stackoverflow.com/questions/456367/reverse-parse-the-output-of-arrays-tostringint

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

rledley
+3  A: 

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(0, 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

levik
In this case, I was using strings, so I guess parsing it myself is simple enough. Thank you.
Of course, this would work only if the strings don't themselves contain the comma characters, which is the first point in my response.
Hemal Pandya
A: 

What does the ArrayList consist of? As others said, it may be impossible in certain cases, but quite possible and guaranteed to work if:

  • each string representation of element of the array can be identified unambiguously (as it can be for example if the ArrayList consists of Integers)

  • there is a way to create an object of original type from its String representation. I find it most elegant to do this using a static method fromString

Of course, this mimics the whole (de)serialization framework.

Hemal Pandya