Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 983
user174772 Avatar asked Oct 05 '09 06:10

user174772


People also ask

How do you reverse part of an ArrayList in java?

We can make use of the In-built Collections. reverse() method for reversing an arraylist.

What is the reverse of Tostring in java?

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.

How do you reverse a string in an ArrayList?

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.

How do you print the elements of an ArrayList in reverse order?

In order to reverse order of all elements of ArrayList with Java Collections, we use the Collections. reverse() method.


2 Answers

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

like image 165
levik Avatar answered Nov 14 '22 21:11

levik


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.

like image 27
rledley Avatar answered Nov 14 '22 23:11

rledley