# Thread: Problem using equal() method

1. Member Join Date
Nov 2008
Posts
9
Rep Power
0

## Problem using equal() method

Instructions:

add an equals method that receives a Rectangle instance and returns true if the length and width are the same as the length and width of the current instance, false otherwise.

My Code:

public class Rectangle
{
private int length;
private int width;

public Rectangle (int length, int width)
{
this.length= length;
this.width=width;
}

public Rectangle ()
{
}
public void setLength(int length)
{
length=length;
}
public void setWidth(int width)
{
width=width;
}
public int getLength ()
{
return length;
}
public int getWidth()
{
return width;
}
public int getArea()
{
return width * length;
}
public boolean equals (Rectangle object 1)
{
boolean status;
if (object1.getLength().equals(Rectangle)
{
status=true;
}
else
{
status=false;
}
return status;

I am not sure what to send the method to compare the current instance and the second instance? Also how to compare the width and length?  Reply With Quote

2. ## When checking for equality, I like to do the following tests first:

1) if rect2 (the parameter passed) == null, return false
2) if rect2 == this (the two objects are the same, return true
3) if !(rect2 instanceof this.getClass()), return false

Then I check to see if the data match. here you want to get this getLength() and rect2.getLength() and check to see if the two ints are ==. Use == here since you're checking equality for primitives. Same for width.  Reply With Quote

3. Member Join Date
Jul 2008
Posts
68
Rep Power
0

## The final step in Fubarable's explanation can be done rather neatly with two set's of == and one set of && all on one line.

Also, since all objects inherit the equals method from Object, you might be able to get an idea of what a good equals method looks like by looking through the java source at the over-rides that have been written.  Reply With Quote

4. Senior Member Join Date
Sep 2008
Posts
564
Rep Power
13

## It seems as if he is not trying to compare actual objects, just their properties (length and width). He just seems to be confused with what to do.

You are correct in getting the input parameter "object1"'s length with "object1.getLength()". However, why are you calling "equals"? Moreover, you cannot call the method as you have, because it is being called on whatever "object1.getLength()" returns, which is an int.

Think of it this way. You want to check if object1 and the object we are in have the same length and width. You use .getLength() to get the length of object1. You want to compare it to the length of the object we are in. How do you get the length of the object? And how do you you compare it?  Reply With Quote

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•