如何将 arrayList.toString() 转换为实际的 arraylist [英] How to convert an arrayList.toString() into an actual arraylist

查看:46
本文介绍了如何将 arrayList.toString() 转换为实际的 arraylist的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的软件中,由于SQLite 中没有Array 数据类型,我将ArrayList 保存为String.现在我需要使用我的数组并希望将其转换回 ArrayList.我该怎么做?

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 and want to convert it back to an ArrayList. How can I do it?

这里有一个例子:

ArrayList<String> list = new ArrayList<String>();
list.add("name1");
list.add("name2");
list.add("name3");
list.add("name4");
list.add("name5");
list.add("name6");

String newList = list.toString();
System.out.println(newList);

结果:[name1, name2, name3, name4, name5, name6]

那么现在如何将其转换为 ArrayList?

So now how can I convert this into an ArrayList<String>?

推荐答案

我相信这应该可行:

Arrays.asList(newList.substring(1, newList.length() - 1).replaceAll("\\s", "").split(","));

  • 取字符串,去掉第一个和最后一个括号.
  • 删除每个空格.
  • 以逗号分隔,作为列表收集.
  • 请注意,如果您真的必须为一个项目执行此操作,那么您的代码设计就有问题.但是,如果这只是出于好奇目的,那么此解决方案将起作用.

    Note that if really you have to do this for a project, then there is something wrong in your code design. However, if this is just for curiosity purpose then this solution would work.

    经过测试

    ArrayList<String> list = new ArrayList<String>();
    list.add("name1");
    list.add("name2");
    list.add("name3");
    list.add("name4");
    list.add("name5");
    list.add("name6");
    
    String newList = list.toString();                
    List<String> myList = Arrays.asList(newList.substring(1, newList.length() - 1).replaceAll("\\s", "").split(","));
    
    System.out.println(myList);
    

    会正确编译并打印:

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

    <小时>

    编辑

    根据你的评论,如果你真的希望你的变量是一个 ArrayList 实例,那么你可以将列表传递给 ArrayList 构造函数:

    As per your comments, if really you want your variable to be an ArrayList<String> instance then you could pass the list to ArrayList constructor :

    ArrayList<String> myList = new ArrayList(Arrays.asList(newList.substring(1, newList.length() - 1).replaceAll("\\s", "").split(",")));
    

    你不能直接转换为 Arrays.asList 使用它自己的内置 java.util.Arrays$ArrayList 类.

    You can't cast directly as Arrays.asList use it own builtin java.util.Arrays$ArrayList class.

    这篇关于如何将 arrayList.toString() 转换为实际的 arraylist的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆