键入数组时for循环和每个循环之间的区别

时间:2015-08-16 02:37:09

标签: java

public class WeightedQuickUnionUF {
    private int[] id;
    private int[] sz;

    public WeightedQuickUnionUF(int N){
        id = new int[N];
        sz = new int[N];
        for(int i=0;i<N;i++)
            id[i] = i;
        for(int j=0;j<N;j++)
            sz[j] = 1;
    } 

    // find the root of that number
    public int root(int p){
        while(p != id[p])
            // // Follow links to find a root.
            p = id[p];
        return p;
    }

    public int getid(int p){
        return id[p];
    }
    public int getsize(int p){
        return sz[p];
    }

    // print the array
    // I use 2 ways to print the final array, but the results are different
    public void show(){
        for(int ele:id)
            System.out.print(id[ele]+ " ");
        for(int j=0;j<id.length;j++)
            System.out.print(id[j]+ " ");
        System.out.print("\n");
    }
    // link two trees, the root of the smaller one will be linked to the
    // root of the larger one 
    public void union(int p, int q){
        int rootp = root(p);
        int rootq = root(q);
        if(sz[rootp] < sz[rootq]){
            id[rootp] = rootq;
            sz[rootq] += sz[rootp];
        }
        else{
            id[rootq] = rootp;
            sz[rootp] += sz[rootq];
        }
    }
    // test the class I have defined
    public static void main(String args[]){
        WeightedQuickUnionUF test1 = new WeightedQuickUnionUF(10);
        test1.union(6, 0);
        test1.union(1, 7);
        test1.union(7, 9);
        test1.union(8, 9);
        test1.union(8, 5);
        test1.union(4, 2);
        test1.union(9, 3);
        test1.union(4, 0);
        test1.union(3, 0);
        test1.show();
    }
}

我的问题是关于函数show()的性能。我使用2种方法打印相同的数组,但结果不同。 这段代码的正确输出应该是6 1 4 1 1 1 4 1 1 1,这意味着for循环可以给我正确的答案。但是每个循环都不能做正确的事情。

1 个答案:

答案 0 :(得分:3)

for-each loop并不像您期望的那样行事。也就是说,

dispatch_async()

应该是(我建议使用大括号)

for(int ele : id)
    System.out.print(id[ele]+ " ");