• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Tim Cooke
  • Paul Clapham
  • Jeanne Boyarsky
Sheriffs:
  • Ron McLeod
  • Frank Carver
  • Junilu Lacar
Saloon Keepers:
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Al Hobbs
  • Carey Brown
Bartenders:
  • Piet Souris
  • Frits Walraven
  • fred rosenberger

equals() doubt

 
Ranch Hand
Posts: 383
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
int[]a = new int[]{1};
int[]b = new int[]{1};
System.out.println(a.equals(b));

Why this code snippet prints "false".
 
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I don't see anything in the JLS about the equals method in an array. I would assume that the method is not overridden, and therefore has the behavior inherited from Object (a simple comparison of object references).

If you want to compare arrays for equality, you might consider using an equals method from the Arrays (note the 's' on the end) class.
[ August 30, 2007: Message edited by: marc weber ]
 
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
if your code change like:
int[]a = new int[]{1};
int[]b = new int[]{1};
System.out.println(Arrays.equals(a,b));

the output will be true
becase the default equals method is inherited from Object;
 
Ranch Hand
Posts: 274
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by dolly shah:
int[]a = new int[]{1};
int[]b = new int[]{1};
System.out.println(a.equals(b));

Why this code snippet prints "false".



It is giving false, because as the equals() method is not implemented, the default implementation of equals() is using ==, which returns false.

Having same number/same elements in an array doesn't mean they will pass equals test.

Gitesh
 
A berm makes a great wind break. And we all like to break wind once in a while. Like this tiny ad:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic