# Problem using equal() method

• 11-18-2008, 04:50 AM
ookie833
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?
• 11-18-2008, 04:56 AM
Fubarable
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.
• 11-18-2008, 05:35 AM