1

The following:

class ArrayCompare 
{
    public static void main (String[] args) 
    {
        int []arr1 = {1, 2, 3, 4, 5};
        int []arr2 = {1, 2, 3, 4, 5};
        System.out.println("arr1 == arr2 is " + (arr1 == arr2));
    }
}

Returns arr1 == arr2 is false

Why is this? Why is arr1 Equals to arr2 is false.

Should this not be true?

Eran
  • 387,369
  • 54
  • 702
  • 768
Sempliciotto
  • 107
  • 1
  • 2
  • 6
  • 1
    The contents of the arrays are equal. But each one is a reference to a different object. – barak manos Nov 10 '14 at 11:38
  • 1
    possible duplicate of [comparing arrays in java](http://stackoverflow.com/questions/5588460/comparing-arrays-in-java) – JJJ Nov 10 '14 at 11:40
  • Off-site resource that has nice pictures that can really help to visualize this: http://www.javaranch.com/campfire/StoryPassBy.jsp – Gimby Nov 10 '14 at 13:52

4 Answers4

9

No it should not be true. You are comparing the references of two distinct objects, so == should return false.

Use Arrays.equals(arr1,arr2) if you wish to compare the contents of the two arrays.

Eran
  • 387,369
  • 54
  • 702
  • 768
0

Java eye is not human eye.

Though the content is same, since both references are pointing to difference Objects , == returns false.

System.out.println(Arrays.equals(arr1, arr2)); // prints true
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
0

You are trying to compare references of two different objects using == so therefore it returns false. To compare the contents use:

 Arrays.equals(arr1, arr2);

Also, might be worth reading the following Java == vs .equals() confusion

Community
  • 1
  • 1
Harry
  • 3,031
  • 7
  • 42
  • 67
0

arr1.equals(arr2) is the same as arr1 == arr2, i.e. is it the same array, i.e. whether the references (pointers) are same. Use:

Arrays.equals(arr1, arr2);

to compare the contents of the arrays. This will return true if the two specified arrays of ints are equal to one another. So, use:

System.out.println("arr1 == arr2 is " + Arrays.equals(arr1, arr2));
Dr. Debasish Jana
  • 6,980
  • 4
  • 30
  • 69