转换为实际的arraylist

转换为实际的arraylist

本文介绍了如何将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<String>?

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<String>实例,则可以将列表传递给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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 18:15