我有两个arrayList
ArrayList ar1 = new ArrayList();
ArrayList ar2 = new ArrayList();
ar1 的值为{A,B,C,D} ar2 的值为{1,2,3,4}
我想添加这两个数组列表 输出应该是
A 1 B 2 C 3 D 4
我用过 ar1.addrange(AR2); 输出是这样的 一个 乙 C d 1 2 3 4
有任何建议如何解决这个问题?
答案 0 :(得分:2)
这应该可以解决问题。
int max = Math.Max(ar1.Count, ar2.Count);
ArrayList ar3 = new ArrayList();
for (int i=0; i < max; i++)
{
if (i < ar1.Count)
{
ar3.Add(ar1[i]);
}
if (i < ar2.Count)
{
ar3.Add(ar2[i]);
}
}
答案 1 :(得分:2)
答案 2 :(得分:1)
尝试创建一个新的ArrayList来保存解决方案......
ArrayList ar3 = new ArrayList();
for (int i = 0; i < ar1.Length; i++)
{
ar3.Add(ar1[i]);
ar3.Add(ar2[i]);
}
答案 3 :(得分:1)
使用一个列表,以免你拳击! (假设数组长度相等)
List<Int32> fun = new List<Int32>();
for (Int32 i = 0; i < ar1.Length; ++i)
{
fun.Add(ar1[i]);
fun.Add(ar2[i]);
}
答案 4 :(得分:1)
一种并行化解决方案,在元素数量较多的情况下,可以产生更好的时间性能(大约两倍),无需额外空间:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
public class Main {
public static void main(String[] args) {
final ArrayList ar1 = new ArrayList();
ar1.add("A");
ar1.add("B");
ar1.add("C");
ar1.add("D");
final ArrayList ar2 = new ArrayList();
ar2.add("1");
ar2.add("2");
ar2.add("3");
ar2.add("4");
//Create a hashmap with size and loadfactor that prevent it
//from being expanded before filling it.
final HashMap ar3 = new HashMap(10, 0.9f);
//fill half the list by a thread
Thread thread1 = new Thread(){
@Override
public void run() {
int i = 0;
for (Iterator it = ar1.iterator(); it.hasNext();) {
ar3.put(i, it.next()) ;
i+=2;
}
}
};
//fill half the list by another thread
Thread thread2 = new Thread(){
@Override
public void run() {
int j = 1;
for (Iterator it = ar2.iterator(); it.hasNext();) {
ar3.put(j, it.next()) ;
j+=2;
}
}
};
//start threads
thread1.start();
thread2.start();
//Let main waits for them
try {
thread1.join();
thread2.join();
} catch (InterruptedException ex) {
System.out.println(ex);
}
//print result
System.out.println(ar3.values());
}
}
答案 5 :(得分:0)
尝试以下代码,它应该可以正常工作:
public static void main(String[] args) throws ParseException
{
List<String> arr1 = new ArrayList<String>();
arr1.add("1");
arr1.add("2");
arr1.add("3");
arr1.add("4");
List<String> arr2 = new ArrayList<String>();
arr2.add("A");
arr2.add("B");
arr2.add("C");
arr2.add("D");
List<String> arr3 = mergeList(arr1, arr2);
for (String string : arr3)
{
System.out.println(string);
}
}
public static List<String> mergeList(List<String> arr1, List<String> arr2)
{
int i = 0;
int size = arr2.size();
for (String string : arr1)
{
if (size >= (i + 1))
{
arr2.add(i + 1, string);
i = i + 2;
}
else
{
arr2.add(string);
}
}
return arr2;
}