I have a small query which i could not understand.
Today i was going through sourcecode of java.util package and had a little doubt.
Why all AbstractList subclasses overrides contains method again?
For example:
Source Code for contains method in AbstractCollection class.
public boolean contains(Object o) {
Iterator<E> e = iterator();
if (o==null) {
while (e.hasNext())
if (e.next()==null)
return true;
} else {
while (e.hasNext())
if (o.equals(e.next()))
return true;
}
return false;
}
SourceCode for overrided contains() method for ArrayList subclass.Similarly other subclasses have their own implementation version.
public boolean contains(Object elem) {
return indexOf(elem) >= 0;
}
public int indexOf(Object elem) {
if (elem == null) {
for (int i = 0; i < size; i++)
if (elementData[i]==null)
return i;
} else {
for (int i = 0; i < size; i++)
if (elem.equals(elementData[i]))
return i;
}
return -1;
}
Please can anyone try to explain why the need to override instead of use the superclass implementation directly.
I predict it is because of of performance gain we may achieve when we iterate through indexing?
2 comments:
not sure 100% but my say --util api like arrayList etc, has their own implementation of the interface so that user using respective api methods get the data accordingly.
For eg: data inside set and list implementations varies but use method same implementation method names from interfaces.
Anonymous,
Thanks for your reply.Hey i even think it may be related to performance improvement etc...
Thanks
Prashant
Post a Comment