Re: Error in the equal method of generic Pair class
This message is in MIME format. The first part should be readable text,
while the remaining parts are likely unreadable without MIME-aware tools.
---910079544-2005488634-1217374526=:16575
Content-Type: TEXT/PLAIN; charset=ISO-8859-1; format=flowed
Content-Transfer-Encoding: 8BIT
On Tue, 29 Jul 2008, puzzlecracker wrote:
On Jul 29, 9:47?am, Tom Anderson <t...@urchin.earth.li> wrote:
On Mon, 28 Jul 2008, puzzlecracker wrote:
public class Pair <T, U>
{
? ?@Override
? ?public boolean equals( Object o )
? ?{
? ? ? ? ? ?if ( this == o )
? ? ? ? ? ?{
? ? ? ? ? ? ? ? ? ?return true;
? ? ? ? ? ?}
? ? ? ? ? ?if ( o == null || !(getClass().isInstance( o )) )
? ? ? ? ? ?{
? ? ? ? ? ? ? ? ? ?return false;
? ? ? ? ? ?}
? ? ? ? ? ?Pair<T, U> other = getClass().cast(o);
? ? ? ? ? ?return (first == null? other.first == null : first.equals( other.first ))
? ? ? ? ? ?&& (second == null? other.second == null : second.equals( other.second ));
? ?}
}
This line gives a cast error during compilation: Pair<T, U> other =
getClass().cast(o);
Why can't we use a traditional ?Pair<T, U> other =(Pair<T, U> ) o; ?
Or, you could enter the voodoo wonderland of expert generics, and cast to
Pair<?, ?>. That means a Pair that could have any types as parameters, so
it compiles without warnings (at least, it does under Eclipse). And,
because you're never doing anything with its elements that requires them
to be of any specific type, it should work fine with the rest of your
code.
Hey would you exemplify in my equal method how to do that - Pair<?, ?>
in the context of the cast?
public class Pair<T, U> {
public final T first ;
public final U second ;
public Pair(T first, U second) {
this.first = first ;
this.second = second ;
}
public boolean equals(Object obj) {
if (obj == this) return true ;
if (obj == null) return false ;
if (!(obj instanceof Pair)) return false ;
Pair<?, ?> p = (Pair<?, ?>)obj ;
return equals(first, p.first) && equals(second, p.second) ;
}
private static boolean equals(Object a, Object b) {
return (a != null) ? (a.equals(b)) : (b == null) ;
}
}
tom
--
DO NOT WANT!
---910079544-2005488634-1217374526=:16575--