Reputation: 73
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
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
Reputation: 2398
The equality test just compares references, not content, so it will always return false for two different array references.
Upvotes: 0