简体   繁体   中英

what does the equals() exactly comparing when you using it to compare two objects?

here is the class I want to compare:

public class test
{
   private String str=null;
   private int integer=0;
   private double doubleNum=1.1; 
}

now I'm comparing it by instantiate two same classes

public class testEquals
{
   public static void main(String[] args)
   {
      test s1 = new test();
      test s2 = new test();
      System.out.print(s1.equals(s2));
   }
}

the result is

false

Your test class didn't override equals , so it inherits the method from Object :

The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true).

They aren't the same object, so false is returned.

looking at Object.equeals() which is what you are calling, you will see that the default implementation is comparing the object using ==, which is basically comparing the address.

http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7-b147/java/lang/Object.java#149

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM