Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Array Help

 
Hamraj Kulshreshtha
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why the result of the below code is false??


import java.util.*;
class Test
{
public static void main(String[] args)
{
int[] a = new int[]{1};
int[] b = new int[]{1};
System.out.println(a.equals(b));
}
}
 
Deepak Jain
Ranch Hand
Posts: 637
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As you know every arrays is an object of Array class and not Arrays [Arrays is an utility class].When you invoke a.equals(b) it invokes the equals() method of Object class which returns true if both the references refer to same object otherwise returns false.
int[] a = new int[]{1};
int[] b = new int[]{1};
System.out.println(a.equals(b));
Here a and b refer to two different objects and hence returns false.
Hope this clears the answer.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15485
43
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Deepak Jain:
As you know every arrays is an object of Array class and ...

This is not entirely correct. An array is an object, but it is not an instance of a class named Array. An array is not an instance of any class in the Java API; the class for arrays is a special class that is built-in in the JVM.

Anyway, that special class does not have an overridden equals() method, so the default equals() method of class Object is used. That version of equals() just compares the objects with ==, and == only returns true if the two arguments on both sides refer to the exact same object. You obviously have two arrays, so == returns false.

If you want to compare the contents of two arrays, you'll have to loop through the arrays and compare the elements one by one. You could also use one of the utility methods in the class java.util.Arrays:

[ January 10, 2008: Message edited by: Jesper Young ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic