Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

arrays equals() confusion  RSS feed

 
Damodar Mukhopadhyay
Ranch Hand
Posts: 98
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why the following code produce outpt as false???

int[]a = new int[]{1};
int[]b = new int[]{1};
System.out.println(a.equals(b));


Please help...
[ March 12, 2007: Message edited by: Barry Gaunt ]
 
Damodar Mukhopadhyay
Ranch Hand
Posts: 98
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
the above code is modified and it produce true....!!! WHY???

int[] a = new int[]{1};
int[] b = new int[]{1};
System.out.println(Arrays.equals(a,b));
 
Suchen Chodankar
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,



The above code compares the two different object to see whether they are same and not the content of the objects. And since object a and b are two different objects equals method will return false.




But the method Arrays.equals will compare the content of two arrays to see whether they are same. Here the element of array a is {1} and element of array be is also {1} so it return output as true.
 
Damodar Mukhopadhyay
Ranch Hand
Posts: 98
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How the containt of a and b are not same???
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Does a java array have an equals method? If so where does it come from? Answering those two questions will lead you to why the first example gives false.
 
Kunal Gupta
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In case of string equals() method compares the contents.
In case of arrays does it not compare the contents?

And Arrays has an equal method..Can an1 please eloborate on this topic..ITs still unclear.
 
Premak Rajan
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1. int[] a={1};
2. int[] b={1};
3. a.equals(b);

Here a and b is array object,it has no content. So in line it compares to see whether they are same object,but they are different object. So the result is false.

if you compile this line,

a[0].equals(b[0])

the result will be true,here it compares the content of int array
 
Meena R. Krishnan
Ranch Hand
Posts: 178
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Does this even compile? You cannot invoke equals on the primitive type. The following will work

 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!