【发布时间】:2015-01-20 22:39:23
【问题描述】:
有没有可能合并ArrayList的两个元素?
这是我的数组 = [u,s,m,a,t,t]
我想要这样的东西=[us,matt]
我尝试使用 toString() 和 replace('',''),但它合并了整个数组 [usmatt]。
还有其他选择吗?
【问题讨论】:
标签: java arrays arraylist merge tostring
有没有可能合并ArrayList的两个元素?
这是我的数组 = [u,s,m,a,t,t]
我想要这样的东西=[us,matt]
我尝试使用 toString() 和 replace('',''),但它合并了整个数组 [usmatt]。
还有其他选择吗?
【问题讨论】:
标签: java arrays arraylist merge tostring
我不知道你的意思,但你试图达到的目标可以通过这种方式完成:
伪代码:
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]
【讨论】:
试试这个:(对于任何长度的 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);
}
【讨论】: