Reputation: 2664
I am stuck on one component of a java assignment for a data structures class that is preventing me from completing the rest of it. It is a simple concept but I am missing something in the implementation. I have a Dynamic array
called list1
and I need to compare it to another list (list2
). I have a method: equals(Object a)
so the call is list1.equals(list2);
I know how to compare lists with an iterator but how do I reference the list1
Object to compare the two?
I am not asking for you to do my assignment, just help me understand how this would work.
public static void main(String args[])
{
DynamicArrayOfInts list1 = new DynamicArrayOfInts();
}
public DynamicArrayOfInts()
{
storage = new int[INITIAL_CAPACITY];
size = 0;
}
public boolean equals(Object aThat)
{
if(aThat.equals(storage))
return true;
else
return false;
}
Upvotes: 1
Views: 211
Reputation: 13807
you should do something like this:
public boolean equals(Object obj)
{
if(obj == null) return false;
if(obj.getClass() != DynamicArrayOfInts.class) return false;
DynamicArrayOfInts other = (DynamicArrayOfInts) obj;
/*compare this.storage to other.storage with the iterator
or with simple indexing.*/
}
Upvotes: 2
Reputation: 120168
I think you are saying that you do the comparison inside the equals
method. If that is so, you need to cast the argument a
to a list. So
public boolean equals(Object a) {
MyList list1 = (MyList) a;
...
}
The line MyList list1 = (MyList) a
means "treat the reference a
as a reference to an instance of MyList
, and assign it to the reference list1
.
equals
typically takes an Object
so you can pass (almost) anything in to equals
. Depending on the specific case, the first thing you can do is check the type of the argument to equals
and return false if it has no chance of being equal.
Look at this example I found on the intertubes. The first thing you see in their example is
if ( this == aThat ) return true;
if ( !(aThat instanceof Car) ) return false;
doing things like this allows you to return quickly if the comparison is trivial. For example, it's a tautology that an instance is equal to itself; there is no way that cannot be true.
Upvotes: 1
Reputation: 8312
Inside the equals method you use the this
operator to access list1 in place of the nae list1
.
Upvotes: 1