英文:
how to transfer elements from UnorderedList to array using iterable
问题
public class Slope<E> implements Comparable {
private Trail[] trail;
private int ranking;
private int count;
public Slope(ArrayUnorderedList<Trail> path) {
trail = new Trail[10];
Iterator<Trail> iter = path.iterator();
for (int i = 0; i < trail.length; i++) {
while (iter.hasNext()) {
trail[i] = iter.next();
count++;
}
}
}
}
我想使用迭代器逐个将UnorderedList的每个元素传输到trail数组中,但它只会更新数组中的第一个值,其余值仍然指向null。
英文:
public class Slope<E> implements Comparable {
private Trail[] trail;
private int ranking;
private int count;
public Slope (ArrayUnorderedList<Trail> path) {
trail = new Trail[10];
Iterator<Trail> iter = path.iterator();
for (int i = 0; i < trail.length; i++) {
while (iter.hasNext()) {
trail[i] = iter.next();
count ++;
}
}
}
I want to transfer each of the UnorderedList elements to the
trail array one-by-one using the iterator but it only updates the first value in the array and the rest still point to null.
答案1
得分: 0
问题出在你的循环结构上;你对每个i
的值都迭代了一遍iter
。这会导致你只会设置trail[0]
的值,因为一旦你对i=0
迭代完成,它就结束了;对于所有其他i
的值,iter.hasNext()
都将是false
。
要解决这个问题,你需要在没有封闭的for循环的情况下迭代iter
,同时仍然需要跟踪一个运行中的索引,可能会像这样:
public class Slope<E> implements Comparable {
private Trail[] trail;
private int ranking;
private int count;
public Slope(ArrayUnorderedList<Trail> path) {
trail = new Trail[10];
Iterator<Trail> iter = path.iterator();
int i = 0;
while (iter.hasNext() && i < trail.length) {
trail[i++] = iter.next();
count++;
}
}
}
英文:
The issue is with your loop structure; you iterate over iter
for every single value of i
. This will cause you only ever to set the value of trail[0]
because once you have iterated over iter
for i=0
, it's done; iter.hasNext()
will be false
for all other values of i
.
To fix this, you will need to iterate over iter
without an enclosing for-loop while still keeping track of a running index, which might look something like this:
public class Slope<E> implements Comparable {
private Trail[] trail;
private int ranking;
private int count;
public Slope (ArrayUnorderedList<Trail> path) {
trail = new Trail[10];
Iterator<Trail> iter = path.iterator();
int i = 0;
while (iter.hasNext() && i < trail.length) {
trail[i++] = iter.next();
count++;
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论