aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Array Help Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Array Help" Watch "Array Help" New topic
Author

Array Help

Hamraj Kulshreshtha
Ranch Hand

Joined: Oct 06, 2007
Posts: 31
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));
}
}


SCJP 1.5 91%
Deepak Jain
Ranch Hand

Joined: Aug 05, 2006
Posts: 637
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.


SCJP, SCWCD, SCBCD
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14348
    
  22

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 ]

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Array Help