Java LinkedList Iterators: Why are they returning only Objects? -
here, i'll post code:
int len = internallist.size(); listiterator<e> forward = internallist.listiterator( 0 ); listiterator<e> backward = internallist.listiterator( len ); while( forward.hasnext() && backward.hasprevious() ) { e next = forward.next(); e prev = backward.previous(); // when object references same, expect @ // center of list (for odd-numbered lists?); we're done if( next == prev ) return true; // otherwise, if object values aren't same, we're not // palindrome if( !((e)next).equals( prev ) ) return false; }
and here's internal list:
private linkedlist<e> internallist;
so problem last if statement checks object's equals() method; not e's equals(). if forcibly casting doesn't work, does?
the correct implementation of equals(object)
chosen @ runtime, due runtime polymorphism. why think that's not case?
actually, might have made common mistake , implemented equals(aspecifictype)
instead of equals(object)
: want override equals(object)
method java.lang.object
. specifying different parameter type means no longer override method.
a common equals()
implementation aspecifictype
start this:
public boolean equals(object o) { if (this==o) { return true; } else if (o==null || o.getclass() != getclass()) { return false; } aspecifictype other = (aspecifictype) other; // insert specific comparison here return result; }
Comments
Post a Comment