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
?
We can make use of the In-built Collections. reverse() method for reversing an arraylist.
String class in Java does not have reverse() method, however, the StringBuilder class has built-in reverse() method. StringBuilder class do not have toCharArray() method, while String class does have toCharArray() method.
Here, first, we will convert the original string to a character array. Then create an ArrayList object and add the original characters to the ArrayList. Afterward, we will use the reverse() function in the collection framework to reverse the ArrayList.
In order to reverse order of all elements of ArrayList with Java Collections, we use the Collections. reverse() method.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With