【问题标题】:Merge two or more elements of ArrayList合并 ArrayList 的两个或多个元素
【发布时间】:2015-01-20 22:39:23
【问题描述】:

有没有可能合并ArrayList的两个元素?

这是我的数组 = [u,s,m,a,t,t] 我想要这样的东西=[us,matt]

我尝试使用 toString() 和 replace('',''),但它合并了整个数组 [usmatt]。 还有其他选择吗?

【问题讨论】:

    标签: java arrays arraylist merge tostring


    【解决方案1】:

    我不知道你的意思,但你试图达到的目标可以通过这种方式完成:

    伪代码:

    String[] array1 = [u,s,m,a,t,t]
    String a = array[0]+array[1]
    String b = array[2]+array[3]+array[4]+array[5]
    String[] array2 = [a,b]
    

    【讨论】:

    • 是的,但这不是唯一的例子,有时数组更长
    • 所以你想动态地做?是否有一个因素决定了每个单词的长度必须是多少?
    • 是的,但这很难说,因为它只是更大应用程序的一小部分,但感谢您的帮助:)
    • 试着解释一下。
    【解决方案2】:

    试试这个:(对于任何长度的 ArrayList。)

    public static void MergeArrayList() {
        ArrayList<Character> Array = new ArrayList<Character>() {{ add('u');add('s');
                                        add('m');add('a');add('t');add('t');}};
        ArrayList<String> newArray = new ArrayList<>();
        int n=2; // Change this to indicate where you need to make the cut.
        String str="";        
        for (int i=0;i<Array.size();i++) {
            if (i==n) {
                newArray.add(str);
                str="";
            }
            str += Array.get(i);
        }
        newArray.add(str);
        System.out.println(Array);
        System.out.println(newArray);        
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-20
      • 1970-01-01
      • 2014-06-16
      • 2017-04-11
      • 1970-01-01
      • 1970-01-01
      • 2017-08-28
      • 2011-10-10
      相关资源
      最近更新 更多