![]() ![]() Java has a special method for this: equals(). How do we change this behavior and make sure the program outputs the correct result when the DNA matches? But our program and the = operator tell us the opposite. We get the same logical result (because we didn't change much), but now that logic is no good! After all, in real life, DNA analysis should give us a 100% guarantee that we've got twins standing in front of us. It compares the genetic code of two people, and determines whether they are twins. The = operator uses approximately this same logic when we use it to compare two objects.īut what if you need your program to use different logic?įor example, suppose your program performs DNA analysis. That makes you similar in many respects, but you're still not twins - and you're obviously not the same person. Certainly, somewhere in the world there is a person who shares your same name, eye color, age, height, hair color, etc. Imagine a situation where you're comparing people. After all, references car1 and car2 point to two different objects, i.e. Two objects could even have 500 fields with identical values, but comparing them would still yield false. The = operator compares object references, not object properties. Why is it that these two cars are not equal? We assigned them the same properties, but the result of the comparison is false. So in Java, when exactly would object A be equal to object B? Hi! Today we will talk about a very important and interesting topic, namely, comparing objects with objects (Compare Strings and Equals).
0 Comments
Leave a Reply. |