有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java帮助:将字符串转换为ArrayList<Integer>

我有一个一模一样的字符串“[1,2,3,4,5]”。现在我想在Arraylist中添加1,2,3,4,5作为普通元素。最好的方法是什么?一种方法是使用字符串。将元素拆分为一个字符串数组,然后在添加到Arraylist之前迭代并将元素解析为整数,但即使在这种情况下,我也不知道要在中使用的确切正则表达式。拆分功能


共 (3) 个答案

  1. # 1 楼答案

    这是一个JSON字符串,因此您可以使用任何JSON API来读取它

    例如,使用Jackson

    String s = "[1,2,3,4,5]";
    List<Integer> l = new ObjectMapper().reader(List.class).readValue(s);
    
  2. # 2 楼答案

    (艰难的道路)

    首先,移除方括号,然后拆分字符串,最后将拆分数组的每个条目解析为一个整数:

    String s = "[1,2,3,4,5]";
    String x = s.replaceAll("[\\[\\]]", ""); // The regex you need to find "[\[\]], 
                                             // because you want to remove any square
                                             // brackets
    String[] y = x.split(","); // Simply put the separator (a comma in this case)
    int[] z = new int[y.length];
    for(int i = 0; i < y.length; i++){
        z[i] = Integer.parseInt(y[i]);
    }
    

    如果想要列表而不是数组,那么:

    ArrayList<Integer> z = new ArrayList<Integer>();
    for(string t : y) {
        z.add(Integer.parseInt(t));
    }
    
  3. # 3 楼答案

    我想你想要的是:

    public static void main(String[] args) {
    
        String chain = "[1,2,3,4,5]";  //This is your String
        ArrayList<Integer> list = new ArrayList<Integer>();  //This is the ArrayList where you want      to put the String
    
        String chainWithOutBrackets = chain.substring(1,chain.length()-1); //The String without brackets
        String[] array = chainWithOutBrackets.split(",");  //Split the previous String for separate by commas
        for(String s:array){  //Iterate over the previous array for put each element on the ArrayList like Integers
            list.add(Integer.parseInt(s)); 
        }
    }