我创建了一个方法,该方法应交织两个列表对象并返回新的交织后列表。
即。如果aList是[A,C,E,G]& bList是[B,D,F],该方法将返回一个包含[A,B,C,D,E,F,G]的列表
没有编译器错误,当我运行程序时,返回的List为空。我已经发现该程序没有进入for循环,因为出于某种原因,当我创建 newList 时,它的大小为0.
以下是代码:
public static <E> List<E> interweave(List<E> a, List<E> b){
List<E> newList = new ArrayList<E>(a.size() + b.size());
Iterator<E> itrA = a.iterator();
Iterator<E> itrB = b.iterator();
for(int i = 0; i < newList.size(); i++){
if(i%2 == 0)
newList.add(i, itrA.next());
else
newList.add(i, itrB.next());
}
return newList;
}
答案 0 :(得分:6)
我相信这可以通过while(iterator.hasNext())
惯用语:
itrA = a.iterator();
itrB = b.iterator();
while (itrA.hasNext() || itrB.hasNext()) {
if (itrA.hasNext())
newList.add(itrA.next());
if (itrB.hasNext())
newList.add(itrB.next());
}
答案 1 :(得分:1)
可以动态组合列表:
static class InterWeave<T> implements Iterable<T> {
// The lists to be interwoven.
final Iterable<T>[] lists;
public InterWeave(Iterable<T>... lists) {
this.lists = lists;
}
@Override
public Iterator<T> iterator() {
return new WeaveIterator();
}
private class WeaveIterator implements Iterator<T> {
// Which list to offer next.
int whichList = 0;
// The Iterators of those lists.
final List<Iterator<T>> iterators = new ArrayList(lists.length);
// The current iterator.
Iterator<T> i;
// The next to deliver - null menas not primed yet.
T next = null;
public WeaveIterator() {
// Take some iterators.
for (Iterable<T> l : lists) {
if (l != null) {
iterators.add(l.iterator());
}
}
}
@Override
public boolean hasNext() {
// Have we already prepared one?
if (next == null) {
// Grab the next iterator and step on.
i = iterators.get(whichList++);
// detect that we're back at start.
Iterator<T> start = i;
// Cycle around the iterators.
whichList %= iterators.size();
while (!i.hasNext()) {
// Get next one.
i = iterators.get(whichList++);
whichList %= iterators.size();
if (i == start) {
// Stop here if we've gone all the way around.
break;
}
}
if (i.hasNext()) {
next = i.next();
}
}
return next != null;
}
@Override
public T next() {
if (hasNext()) {
T n = next;
// Mark it used.
next = null;
return n;
} else {
throw new NoSuchElementException();
}
}
}
}
public void test() {
List<String> a = Arrays.asList(new String[]{"A", "C", "E", "G"});
List<String> b = Arrays.asList(new String[]{"B", "D", "F"});
for (String s : new InterWeave<String>(a, b)) {
System.out.println(s);
}
}