brian Chiem
brian Chiem

Reputation: 245

copy element of array

I can't figure out why isn't the code copying the unique elements to another array. Here is my code. I though that the == is to copy the element, but I got an error, so I used the = instead.

 public static void main(String[] args) {
    // TODO Auto-generated method stub
    int[] B = new int[15];
    B[2] = 2;
    B[3] = 3;
    B[4] = 4;
    B[5] = 5;
    B[6] = 6;
    B[7] = 7;
    B[8] = 8;
    B[9] = 9;
    B[10] = 10;

    int[] check = new int[B.length];
    for (int i = 0; i < B.length; i++) {
        for (int x = 0; x < check.length; x++) {
            if (B[i] != check[x]) {
                check[x] = B[i];
            }
        }
    }

    for (int i = 0; i < check.length; i++) {
        System.out.println(check[i]);
    }
}

Upvotes: 0

Views: 156

Answers (3)

BlackJoker
BlackJoker

Reputation: 3191

== is for test of equalation,= is for assignment,

by the way ,use System.arraycopy(xxx) to copy arrays.

public int[] findUnique(int[] data) {
    int[] unique = new int[data.length];
    int x = 0;
    for (int i = 0; i < data.length; i++) {
        boolean uni = true;
        for (int j = i + 1; j < data.length; j++) {
            if (data[i] == data[j]) {
                uni = false;
                break;
            }
        }
        if (uni) {
            unique[x++] = data[i];
        }
    }
    return unique;
}

Upvotes: 1

DHall
DHall

Reputation: 393

You're looping over everything twice, when it should just be once.

Currently it looks like this:

for (int i = 0; i < B.length; i++) {
    for (int x = 0; x < B.length; x++) {
        if (B[i] != check[x]) {
            check[x] = B[i];
        }
    }
}

This means that when i = 0 , then x=0, 1, 2, 3, 4, etc.. . Then when i = 1, x=0,1,2,3.... , etc.

So the last run will be i=14, where B[i] = 0.
So for every check[x], it won't be equal to 0.

What you want to do is handle it in a line. So instead of 2 variables i and x you can just use i and the outer loop, like this. This means that you're only comparing B[1] to check[1] and B[2] to check[2], and so on.

Like this:

for (int i = 0; i < B.length; i++) {
    if (B[i] != check[i]) {
        check[i] = B[i];
    }
}

Upvotes: 2

Jiri Kremser
Jiri Kremser

Reputation: 12837

System.arrayCopy() is much faster

Upvotes: 0

Related Questions