这个程序是功课。我们已经完成了它,并且很好去。我想知道是否有更简化的写这个程序的方式?该程序被称为Interleave,它所做的是将两个ArrayLists组合起来,以便第一个ArrayList中的每个其他元素都来自第二个ArrayList。听起来很简单,就是我们使用迭代器来添加必要的元素。但代码是BLOCKY。在我看来,必须有更好的方式来写这个,对吧?提前致谢。一个更有效的方法来编写这个程序
import java.util.*;
public class Interleave
{
public static void main(String[] args)
{
ArrayList<Integer> a1 = new ArrayList<Integer>();
Collections.addAll(a1, 10, 20, 30);
ArrayList<Integer> a2 = new ArrayList<Integer>();
Collections.addAll(a2, 4, 5, 6, 7, 8, 9);
System.out.println(a1);
System.out.println(a2);
System.out.println(interleave(a1, a2));
ArrayList<String> list = new ArrayList<String>();
String[] words =
{ "how", "are", "you?" };
for (String s : words)
{
list.add(s);
}
}
public static ArrayList<Integer> interleave(ArrayList<Integer> a1,
ArrayList<Integer> a2)
{
Iterator<Integer> it = a2.iterator();
int i = 1;
while (it.hasNext())
{
int val = it.next();
if (a1.size() >= i)
{
a1.add(i, val);
} else
{
a1.add(val);
}
i += 2;
}
return a1;
}
}
的Java,作为一种语言,是相当冗长和 “块状”。习惯它。 ;-) – Santa 2011-05-18 18:31:26
@Santa,好吧,至少他的项目不涉及乐高积木,那会变得混乱。也许甚至'块';) – FreeSnow 2011-05-18 18:32:59
你可以用一个for each-loop替换Iterator-while循环,这将为你节省一条高高的线!;) – Jacob 2011-05-18 18:34:17