I have this code:
ArrayList<String> list = new ArrayList<>();
String str = list.toString(); // Stored in a database
Is there a quick way to recover the ArrayList from the string ?
I have this code:
ArrayList<String> list = new ArrayList<>();
String str = list.toString(); // Stored in a database
Is there a quick way to recover the ArrayList from the string ?
No, there is no reliable way to do that.
Consider the following:
List<String> list = new ArrayList<>();
list.add("A");
list.add("B, C"); // this contains commas
list.add("D");
System.out.println(list); // [A, B, C, D] : Note, only three elements were added
A couple of solutions:
toString()
.There is no one-size-fits-all solution because ArrayList.toString()
method will print all the elements separated by comma. But there is absolutely no way to find out whether the comma in your outputted string is because of separation of elements or was it literally included in the string (or object).
Consider these two code snippets:
List<String> list = new ArrayList<>();
list.add("one");
list.add("two, three");
System.out.println(list); // [one, two, three]
and
List<String> list = new ArrayList<>();
list.add("one");
list.add("two");
list.add("three");
System.out.println(list); // [one, two, three]
As you can see, both of these examples are giving exactly the same output.
However, if the elements in your list are some other type, (let's say Integer, Double etc... or even String without a comma), Then you can simply get your list back using
Arrays.asList(outString.split(",\\s"));
Sure, you can do it.
ArrayList<String> list = new ArrayList<>();
String str = list.toString();
int len = str.length();
str = str.substring(1, len-1);
String[] parts = str.split(",");
List<String> list2 = Arrays.asList(parts);
But this has one limitation. If any value of list
contaion comma(,) then it will give you wrong output. In that case you should escape comma before convert it to String. Or you can use any serialization mechanism like JSON
Another approach is, do not call toString()
directly. Instead you can use String Joiner
(Example can be found here). Use any safe character. Then split your string to get the list back.