Spano
Spano

Reputation: 73

how to compare duplicated arrays

Recently, I figured you can duplicate a array like this

System.arraycopy(src,0,dup,0,src.length);

However, even though the two arrays are the same, when you compare them using

if(src==dup)
   ...//print true
else if(src!=dup)
   ...//print false

It would always print false. Are there anyways to duplicate an array that does not change with the original one while also being able to compare those two correctly?

Upvotes: 1

Views: 45

Answers (3)

amahfouz
amahfouz

Reputation: 2398

You need to use

Arrays.equals()

Upvotes: 0

Khaled Hassan
Khaled Hassan

Reputation: 166

Just as amahfouz stated in his answer, the references of two different arrays are compared (in the way you wrote in your post).

So, to be able to compare the elements, you should loop through them.

You can import Java.util.Arrays, and do this:

if(Arrays.equals(src, dup))
    System.out.println("Equal");
else
    System.out.println("Not Equal");

Upvotes: 1

amahfouz
amahfouz

Reputation: 2398

The equality test just compares references, not content, so it will always return false for two different array references.

Upvotes: 0

Related Questions