如何使用可迭代对象将UnorderedList中的元素转移到数组中

huangapple go评论74阅读模式
英文:

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&lt;E&gt; implements Comparable {
	
	private Trail[] trail;
	private int ranking;
	private int count;
	
	public Slope (ArrayUnorderedList&lt;Trail&gt; path) {
		trail = new Trail[10];
		
		Iterator&lt;Trail&gt; iter = path.iterator();
		for (int i = 0; i &lt; 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&lt;E&gt; implements Comparable {
    
    private Trail[] trail;
    private int ranking;
    private int count;
    
    public Slope (ArrayUnorderedList&lt;Trail&gt; path) {
        trail = new Trail[10];
 
        Iterator&lt;Trail&gt; iter = path.iterator();
        int i = 0;
        while (iter.hasNext() &amp;&amp; i &lt; trail.length) {
            trail[i++] = iter.next();
            count++;
        }
    }
}

huangapple
  • 本文由 发表于 2020年7月28日 22:16:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/63136218.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定