How to convert an arrayList.toString() into an actual arraylist

前端 未结 3 1775
无人及你
无人及你 2021-01-20 14:06

In my software, since there is no Array data type in SQLite, I saved my ArrayList as a String. Now I need to use my array

3条回答
  •  耶瑟儿~
    2021-01-20 14:42

    This is not possible to do without ambiguity. Consider:

    ArrayList list = new ArrayList();
    list.add("name1, name2");
    list.add("name3, name4");
    list.add("name5");
    list.add("name6");
    
    String newList = list.toString();
    System.out.println(newList);
    
    Result: [name1, name2, name3, name4, name5, name6]
    

    In order to accurately recover the original elements in the general case, your string format must be smarter than ArrayList.toString(). Consider a pre-defined way of encoding lists of strings, perhaps a JSON array, which would result in something like this for my example:

    ["name1, name2", "name3, name4", "name5", "name6"]
    

    JSON also defines how to handle strings with quotes via escaping and/or use of alternate string start/end characters ' and ":

    ["he said, 'hello'", 'she said, "goodbye"', 'I said, "it\'s raining"']
    

    (I also agree with other commenters that your database design should be reconsidered, but wanted to provide a clear answer illustrating the issues with string encodings of lists.)

提交回复
热议问题