0

Hello, I have a question about the code below

// Checks the vertex a
     if (this.a != ((Triangle)o).a)
     {
         return false;
      }

So In a method called Triangle i declared an instance variable like this:

private java.awt.Point a

What I think this code is doing is that this.a is comparing its point value (a.x and a.y) and checking to see if they are equal to that of the o Triangle point (o.a.x and o.a.y) is my interpretation correct?

2
Contributors
1
Reply
2
Views
6 Years
Discussion Span
Last Post by jon.kiparsky
0

I'm pretty sure it's not correct. What you're comparing here is identity. This returns true only in the case that the address contained in this.a is the same as the address contained in o.a. You're comparing pointers.
So if you declare this.a to be a new Point(5,5), and you'd previously declared o.a to be a new Point(5,5), they're different Points with the same value.

Any time you're comparing objects, you always use the .equals() method, if you know that it's been implemented correctly. If not, you have to compare fields, if you can get at all of the relevant fields.

In this case, if your Triangle has three Points, you can rely on Point.equals() to compare correctly.

Now, as an aside what happens if you have Triangle A with
a = (3,4) b = (4,5) and c= (5, 4)
and Triangle B with

a = (4,5) b= (5, 4) and c = (3,4)

Are they equal? Does your comparison say they're equal?

Edited by jon.kiparsky: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.